Laravel 9 Resize Image Before Upload Tutorial

Hello Artisan,

In this Laravel 9 image resize example, I will show you how to resize an image in Laravel and then how to upload it to the server. I am going to use Laravel 9 application to create this image resize and upload. This example will give you step by step image guide on how to resize images in the Laravel 9 application.

To create this Laravel 9 intervention image resize tutorial, we will see, How to resize images before uploading examples in Laravel. You know that Laravel intervention image upload, we use intervention/image package.

In this Laravel 9 resize the image before upload tutorial, I will create a custom trait to resize the image. From that custom trait, I will create a helper method to get an upload file URL and we will resize an image in that method. 

You are going to learn Laravel 9 compress images before uploading from this Larave resize images example. So if you still don't know how to resize images in Laravel 9 then this example is going to be the perfect example for you.

You know that PHP Laravel intervention is a very popular package for resizing images and it provides a resize function that will take three parameters. three parameters are width, height, and a callback function. the callback function is optional.

So, let's follow the below steps to generate a thumbnail image and upload it into the server in the Laravel 9 application.

 

Step 1: Download Laravel

To create Laravel 9 resize image tutorial, we need a fresh Laravel app. So run the below command to download a Laravel application.

composer create-project --prefer-dist laravel/laravel blog

 

Step 2: Install Intervention Package

As we need to resize images before uploading to Laravel, we need this image intervention package. So run the below command to install it.

composer require intervention/image

 

Now we need to add the below code to the following path and alias in config/app.php file so open that file and add the below code.

config/app.php

return [

    ......

    $provides => [

        ......

        ......,

        Intervention\Image\ImageServiceProvider::class

    ],

    $aliases => [

        .....

        .....,

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

    ]

]

 

Now we are completely ready to use this image resizing package in our Laravel application.

 

Step 3: Create Model

As are going to create an image upload system in Laravel with image resizing, so we need a table with an image field. So run below command to create a model:

php artisan make:model Product -m

 

Now update product migration file like below:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->mediumText('description')->nullable()->default('This is product description');
            $table->integer('price');
            $table->integer('qty');
            $table->string('image')->nullable();
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

 

And update product models like:

app\Models\Product.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'price', 'qty', 'image'
    ];

}

 

Now run php artisan migrate command to migrate the database.

 

Step 4: Create Custom Helper Trait

In this step, we will create a custom helper trait to upload an image in Laravel with image resizing. So create a trait like below:

app\Helper\File.php

namespace App\Helper;

use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

Trait File
{   
    public $public_path = "/public/uploadedImages/";
    public $storage_path = "/storage/uploadedImages/";

    public function file( $file, $path, $width, $height ) : string
    {
       if ( $file ) {

           $extension       = $file->getClientOriginalExtension();
           $file_name       = $path.'-'.Str::random(30).'.'.$extension;
           $url             = $file->storeAs($this->public_path,$file_name);
           $public_path     = public_path($this->storage_path.$file_name);
           $img             = Image::make($public_path)->resize($width, $height);
           $url             = preg_replace( "/public/", "", $url );
           return $img->save($public_path) ? $url : '';
       }
    }
}

 

Step 5: Create Route

In this step, we need a route to store our resizing image into a database and storage folder in Laravel. So add the below route:

routes/web.php

Route::get('/product/{id}', 'ProductController@index');
Route::post('/product', 'ProductController@store')->name('store');

 

Read also: Laravel 9 Upload Image to Storage Folder Example

 

Step 6: Create Controller

In this step, we have to create a productController.php file to create the above method to upload and resize in Laravel.

app\Http\Controllers\productController.php

namespace App\Http\Controllers;

use App\Helper\File;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{   
   use File;

   public function index()
   {
      return view('welcome');
   }

   public function store(Request $request){

      if( $file = $request->file('image') ) {
            $path = 'products/images';
            $url = $this->file($file,$path,300,400);
        }

        $product = new Product();
        $product->name = $request->name;
        $product->description = $request->description;
        $product->price = $request->price;
        $product->qty = $request->qty;
        $product->image = $url;

        if($product->save()){
            return back()->with('message','Product Created Successfully!')
        }
   }
}

 

Step 7: Create Blade File

In this step, we have to create a welcome.blade.php file to create an HTML form to save an image with resizing in Laravel. So create it.

resources/views/welcome.blade.php

 

Almost all are set to go. Now we have to run the below command before storing data. run php artisan storage:link to link storage to the public directory. Now you can test by starting the server by running the php artisan serve command.

 

Recommended: Encrypt File Before Uploading and Download Example in Laravel

 

Now after storing and fetching the image, you can print it in your blade file like:

 

Read also: Upload Large CSV File using Queue Job Batching in Laravel

 

Hope this Laravel 9 resize image before upload tutorial will help you.

 

#laravel #laravel-9x #image-upload #interventionimage-package