Eden WebStudio
Eden WebStudio

Reputation: 788

How to save uploaded image to Storage in laravel?

I am using Image intervention to save an image to the storage folder. I have the code below and it seems to just save a file name with a blank image. I think I need a way for the file contents to be written to the folder but struggling for the snippet.

if ($request->hasFile('photo')) {
    $image = $request->file('photo');
    $fileName = time() . '.' . $image->getClientOriginalExtension();

    $img = Image::make($image->getRealPath());
    $img->resize(120, 120, function ($constraint) {
        $constraint->aspectRatio();                 
    });
                
    //dd();
    Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');

Upvotes: 17

Views: 105070

Answers (5)

iohan sandoval
iohan sandoval

Reputation: 369

This work for me in laravel 10

$folder = 'folder/';
$path = storage_path('app/public/'.$folder);
if ($request->hasFile('image')) {
    $image = ImageManager::imagick()->read($file);
    $image->save($path.$filename);
}

Upvotes: 1

Dhana
Dhana

Reputation: 61

if ($request->hasFile('photo')) {
    // $path = Storage::disk('local')->put($request->file('photo')->getClientOriginalName(),$request->file('photo')->get());
    $path = $request->file('photo')->store('/images/1/smalls');
    $product->image_url = $path;
}

Upvotes: 3

Avik Aghajanyan
Avik Aghajanyan

Reputation: 1023

You need to do

if ($request->hasFile('photo')) {
    $image = $request->file('photo');
    $fileName = time() . '.' . $image->getClientOriginalExtension();
    
    $img = Image::make($image->getRealPath());
    $img->resize(120, 120, function ($constraint) {
        $constraint->aspectRatio();                 
    });
    
    $img->stream(); // <-- Key point
    
    //dd();
    Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');
}

Upvotes: 21

Tamil
Tamil

Reputation: 391

Simple Code.

if($request->hasFile('image')){
    $object->image = $request->image->store('your_path/image');
}

Thanks.

Upvotes: 2

dipenparmar12
dipenparmar12

Reputation: 3455

Here is another way to save images using intervention package on storage path with desired name. (using Storage::putFileAs method )

public function store(Request $request)
{
    if ($request->hasFile('photo')) {

        $image      = $request->file('photo');
        $image_name = time() . '.' . $image->extension();

        $image = Image::make($request->file('photo'))
            ->resize(120, 120, function ($constraint) {
                $constraint->aspectRatio();
             });

        //here you can define any directory name whatever you want, if dir is not exist it will created automatically.
        Storage::putFileAs('public/images/1/smalls/' . $image_name, (string)$image->encode('png', 95), $image_name);
    }
}

Upvotes: 1

Related Questions