phplaravellaravel-8intervention

Laravel 8: How To Use Intervention Image Library Properly


I want to use Intervention Image library for my Laravel project, so I just installed it via Composer and added this line of code to config/app.php:

Intervention\Image\ImageServiceProvider::class,

And also this line was added to aliases part:

'Image' => Intervention\Image\Facades\Image::class,

Now at my Controller I coded this:

class AdminController extends Controller
{
    protected function uploadImages($file)
    {
        $year = Carbon::now()->year;
        $imagePath = "/upload/images/{$year}/";
        $filename = $file->getClientOriginalName();
        $file = $file->move(public_path($imagePath), $filename);
        $sizes = ["300","600","900"];
        Image::make($file->getRealPath())->resize(300,null,function($constraint){
            $constraint->aspectRatio();
        })->save(public_path($imagePath . "300_" . $filename));
    }
}

But as soon as I fill my form to check if it's work or not, this error message pops up:

Error Class 'App\Http\Controllers\Admin\Image' not found

Which means this line:

Image::make($file->getRealPath())->resize(300,null,function($constraint){

So why it returns this error while I've included it already in my project ?!

If you know, please let me know... I would really appreciate that.

Thanks


Solution

  • On config/app.php you need to add :

    $provides => [
        Intervention\Image\ImageServiceProvider::class
    ],
    

    And,

    $aliases => [
    
        'Image' => Intervention\Image\Facades\Image::class
    ]
    

    Now you can call use Image; on the top on your controller :

    use Image;
    
    class AdminController extends Controller
    {
        // ...
    }