Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devkon98's avatar

How to compress an image in laravel

Hello i want to compress an image in laravel but i keep getting error, this is my code.

I have made this code in the resource: 'images' => $this->convertToBase64($this->getImages($this->coordination_id)->pluck('image')) ?? '', by this code i get the name of the image example file/name.jpeg

Then at convertToBase64 i do this code:

public function convertToBase64($imagePaths)
    {
        $encodedImages = [];

        if ($imagePaths) {
            foreach ($imagePaths as $image) {
                $imagePath = Storage::get('public/' . $image);
                $compressedImagePath = Helpers::compressImage($imagePath, 'files/', 80);
                $encodedImage = base64_encode(Storage::get('public/' . $compressedImagePath));
                $encodedImages[] = $encodedImage;
                break;
            }
        }

        return $encodedImages;
    }

And for the compressImage i have this code from internet that i found:

 public static function compressImage($image, $path, $quality)
    {
        $fileName = time().'_'.$image->getClientOriginalName();

        $compressedImage = Image::make($image)
            ->encode('jpg', $quality);

        Storage::disk('public')->put($path . $fileName, $compressedImage);
        $completedPath = $path . $fileName;

        return $completedPath;
    }

The compressImage code works well no need to be changed but the code above is new and is making the error:

"message": "Call to a member function getClientOriginalName() on string",
    "exception": "Error",```
0 likes
2 replies
vincent15000's avatar

getClientOriginalName() can only be used on an image object and not on a string.

Here you are passing the image path to the function, whereas you should pass the image itself.

Helpers::compressImage($imagePath, 'files/', 80)

But the getClientOriginalName() function is only accessible at the moment where you upload a file. Once the file is uploaded, Laravel doesn't know the client original name anymore.

That has nothing to do with the compression.

I suggest you to have a look to the spatie package.

https://spatie.be/docs/laravel-medialibrary/v10/introduction

siangboon's avatar

it seem like your $image getting a string... ensure or double check the result of your "imagePath" before passing to the function...

1 like

Please or to participate in this conversation.