I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}
Related
I'm new to Laravel and using Laravel 6.0. While uploading image I am getting error of SplFileInfo::getSize(): stat failed for C:\xamp\tmp\php14F3.tmp
I searched for solution on google yet couldn't find any solution.
This is my controller function
public function store(PostsCreateRequest $request)
{
//
$input = $request->all();
$user = Auth::user();
if ($request->hasfile('photo_id')) {
$file = $request->file('photo_id');
$name = time() .$size. $file->getClientOriginalName();
$file->move('posts' , $name);
$photo = Photo::create(['path'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->posts()->create($input);
Session::flash('created_post',"The Post has been created");
return redirect('/home');
}
My solution is
use Illuminate\Http\Request; this request instead of old request.
public function saveimage(Request $request){
request()->validate([
'file' => 'required|mimes:jpeg,jpg|max:2048',
]);
if ($files = $request->file('file')) {
$destinationPath = 'public/images/'; // upload path
$profilefile = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profilefile);
$insert['file'] = "$profilefile";
}
$check = Document::insertGetId($insert);
return Redirect::to("home")
->withSuccess('Great! file has been successfully uploaded.');
}
}
Its working fine.
Give the size of the image while giving the validation. The below code is working fine.
public function saveImage(Request $request){
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,jpg,gif,png,svg|max:2048'
]);
$instrument = new \App\Models\Instrument;
$instrument->name = $request->input('name');
$instrument->description = $request->input('description');
$imgfile = $request->file('image');
$instrument->image = $imgfile->getClientOriginalName();
if ($imgfile !== null) {
$filenameWithExt = $imgfile->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $imgfile->getClientOriginalExtension();
$fileNameToStore= $filename.'_'.time().'.'.$extension;
$imgfile->storeAs('public/images', $fileNameToStore);
} else {
//dd("Image Not Uploaded");
}
$instrument->save();
return redirect('/instruments')->with('success', 'Details are uploaded successfully');
}
I am trying to upload an image from my react native project using laravel as my backend framework.
This is the data I send :
I receive a warning that my network request failed.
Here is my backend code :
public function upload(Request $request)
{
$image = $request->get('data');
$name = 'Sup';
Image::make($request->get('data'))->save(public_path('images/').$name);
$fileupload = new Fileupload();
$fileupload->filename=$name;
$fileupload->save();
return response()->json(['message' => 'Success']);
}
I have a function, you can try it!
Please change the path before doing anything else (this is the code used to upload one - multiple files at once)
public function uploadImage (Request $request) {
$files = $request->file('images');
$fileText = '';
foreach($files as $file) {
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = Validator::make(array('file' => $file), $rules);
if($validator->passes()){
$destinationPath = 'storage/images/';
$filename = $file->getClientOriginalName();
$unique_name = md5($filename. time()).$filename;
$upload_success = $file->move($destinationPath, $unique_name);
$fileText .= url('storage/images/' . $unique_name) . '|';
}
}
return rtrim($fileText, '|');
}
When I'm storing an image into a database, then it doesn't upload with base URL. How can resolve this type of problem in Laravel?
public function uploadimage(Request $request)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') . '-' . $filename;
$file->move(public_path('img'), $picture);
$employee_image = Image::create($request->all());
$employee_image->image = $filename;
$employee_image->save();
return response()->json(['message' => 'Image Uploaded Successfully']);
}
return response()->json(['message' => 'Select image first.']);
}
The public_path() function does not intend to be use to serve browser friendly uri, so, you should use \Illuminate\Support\Facades\URL facade instead.
e.g.:
$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();
Source: Laravel.IO
Try this ....
public function uploadimage(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employees = new Image($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$employees->image = '/public/images/'.$fileName ;
}
$employees->save() ;
return response()->json(['message' => 'Image Uploaded Successfully']);
}
I have the following code,
my question is how to modify Request values?
public function store(CategoryRequest $request)
{
try {
$request['slug'] = str_slug($request['name'], '_');
if ($request->file('image')->isValid()) {
$file = $request->file('image');
$destinationPath = public_path('images/category_images');
$fileName = str_random('16') . '.' . $file->getClientOriginalExtension();
$request->image = $fileName;
echo $request['image'];
$file->move($destinationPath, $fileName);
Category::create($request->all());
return redirect('category');
}
} catch (FileException $exception) {
throw $exception;
}
}
But,
on each request the output of
echo $request['image'];
outputs some text like /tmp/phpDPTsIn
You can use the merge() method on the $request object. See: https://laravel.com/api/5.2/Illuminate/Http/Request.html#method_merge
In your code, that would look like:
public function store(CategoryRequest $request)
{
try {
$request['slug'] = str_slug($request['name'], '_');
if ($request->file('image')->isValid()) {
$file = $request->file('image');
$destinationPath = public_path('images/category_images');
$fileName = str_random('16') . '.' . $file->getClientOriginalExtension();
$request->merge([ 'image' => $fileName ]);
echo $request['image'];
$file->move($destinationPath, $fileName);
Category::create($request->all());
return redirect('category');
}
} catch (FileException $exception) {
throw $exception;
}
}
In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that.
You are setting the new filename using
$request->image = ...
but then you are retreiving it using the array accessible interface of the Request class.
Try to set the file name using
$request['file'] = ...
or use the merge() method of the Request class.
Any best way to do this will be gratefull
what this do is grab the input from a form and save it to the database.
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
// $extension =$file->getClientOriginalExtension();
$upload_success = Input::file('path')->move($destinationPath, $filename);
$photo = Photo::find($_POST['id']);
$photo->caption = $_POST['caption'];
$photo->path = $destinationPath . $filename;
$photo->save();
if( $upload_success ) {
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
} else {
return Response::json('error', 400);
}
}
this work just fine but i wonder if there a simplify way to do this like how i can get post data from the form send to update to update the photo information instead of me using the $_POST and get the id from the form parse into the update($id) ect. Thanks
You can use the Input class, instead of accessing the post directly.
I would probably re-write the function a little like this:
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
if( Input::file('path')->move($destinationPath, $filename) )
{
$photo = Photo::find(Input::get('id'));
$photo->caption = Input::get('caption');
$photo->path = $destinationPath . $filename;
$photo->save();
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
}
else
{
return Response::json('error', 400);
}
}
The other option is to extract some of this data directly into your Photo model, and do it in there.