webfuelcode's avatar

How to resize image using spatie/image package

I tried to find any light package to resize the uploaded images for laravel. Image intervention is very heavy for my project, so I took spatie/image.

So here is my controller and please tell me how to use spatie/image https://spatie.be/docs/image/v1/image-manipulations/resizing-images

` public function create(Request $request, Brand $brand) { $validated = $this->validate($request,[ 'name'=>'required|min:4', 'image'=>'required|image' ]);

    if($request->hasFile('image')){
        $filename = time() . '.' . $request->image->getClientOriginalExtension();
        $request->image->storeAs('brand', $filename, 'public');
        
        $validated['image'] = $filename;
    }

    //store
    $brand = Brand::create($validated);

    return redirect()->route('brandindex')->withMessage('Brand created successfully!');
}

`

Where to put the line in this function...

0 likes
5 replies
lat4732's avatar
lat4732
Best Answer
Level 12
if($request->hasFile('image')){
        $filename = time() . '.' . $request->image->getClientOriginalExtension();
        $request->image->storeAs('brand', $filename, 'public');

        Image::load(storage_path('public/brand/' . $filename))
   		    ->width(100)
  			->height(100)
   		    ->save(storage_path('public/brand/' . $filename));
        
        $validated['image'] = $filename;
}

I'm not sure if you can implement the spatie/image inside the store methods. But you could try the code I posted above. Explanation of what it is doing: Saving your image -> Get the image -> Resize it -> Override the original image with the resized one image. Probably there is way more properly way of doing it but I can't help you with more than this.

Snapey's avatar

@Laralex don't get in the habit of just using just a timestamp for the filename. 1 second is a long time and it's quite easy to get separate users uploading at the same time. Also, it definitely does not work if you upload multiple files.

lat4732's avatar

@Snapey Yeah, you're right. I will try to remember this when working with images. Thanks! :)

Please or to participate in this conversation.