Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Resize Images in Laravel 8 Before Uploading to Server

How to upload and resize multiple images in laravel 8?

Todayl, I will give you an example of “How to upload and resize multiple images in Laravel 8”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

image resize package in laravel

resize multiple images in laravel

Upload and resize multiple images in Laravel using Intervention Image

Intervention Image is an open-source PHP image handling and manipulation library. It provides an easier and expressive way to create, edit, and compose images and supports currently the two most common image processing libraries GD Library and Imagick.

Installation

Open the project into the terminal and run this command to install it.

composer require intervention/image

Update Config File :

You need to update your app.php file inside the same config\app.php directory where you need to add the providers and aliases of the package as shown below.

config\app.php

'providers' => [
    ....
    ....
    ....
 
    Intervention\Image\ImageServiceProvider::class,
 
],
'aliases' => [ 
    ....
    ....
    ....
 
    'Image' => Intervention\Image\Facades\Image::class,
 
]

Link File Storage in Laravel Application

Now, we need a storage directory where we save our uploaded images. Laravel Filesystem provides a public disk to store the files. The public disk contains files that are publicly accessible. We will find the uploaded files in the storage/app/public folder. To access these files on the web, we need to create a symbolic link from public/storage to storage/app/public.

Create a symbolic link using the command below:

php artisan storage:link

This command would create a storage folder under the public directory. This is where we store our uploaded images.

Generating Migration

We create a new migration file for the “MultipleImageResizeUploads ” table, In your cmd terminal hit the given below command.

 php artisan make:migration create_multiple_image_resize_uploads_table

Migration Structure

<?php

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

class CreateMultipleImageResizeUploadsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('multiple_image_resize_uploads', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->longText('product_images');
            $table->timestamps();
        });
    }

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

Run Migration

php artisan migrate

Create a Model

php artisan make:model Multipleimageresizeupload

App\Models\Multipleimageresizeupload .php

<?php

namespace App\Models;

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

class Multipleimageresizeupload extends Model
{
    use HasFactory;
    protected $table="multiple_image_resize_uploads";
}

Create a Controller

php artisan make:controller ResizemultipleImagesController 

Define Web Routes

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ResizemultipleImagesController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

#Upload and Resize Multiple Images in Laravel
Route::get('/images-upload',[ResizemultipleImagesController::class, 'create']);
Route::post('/images-store',[ResizemultipleImagesController::class, 'store'])->name('images.store');
Route::get('/images-list',[ResizemultipleImagesController::class, 'list'])->name('images.list');

app\Http\Controllers\ResizemultipleImagesController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Image;
use Session;
use Illuminate\Support\Facades\Storage;
use App\Models\Multipleimageresizeupload;

class ResizemultipleImagesController extends Controller
{
    public function create(){
        return view('resize_multiple_images_example.create');
    }

    public function store(Request $request)
    {
       #Handle File  images
       $this->validate($request, ['product_imgs' => 'required', 'product_imgs.*' => 'required|image|max:1999']);
 
          if($request->hasFile('product_imgs')) {
            foreach($request->file('product_imgs') as $file){
 
            //get filename with extension
            $name = uniqid() . '_' . time(). '.' . $file->getClientOriginalExtension();
            $filenamewithextension = $file->getClientOriginalName();
            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
            $Imgdata[] = $name;
            //get file extension
            $extension = $file->getClientOriginalExtension();
            //filename to store
            $filenametostore = $name;
 
            Storage::put('public/product_images/'. $filenametostore, fopen($file, 'r+'));

            //Resize image here
            $thumbnailpath = public_path('storage/product_images/'.$filenametostore);
            $img = Image::make($thumbnailpath)->resize(300, 100, function($constraint) {
                $constraint->aspectRatio();
            });
            $img->save($thumbnailpath);
            }
                $data = new Multipleimageresizeupload();
                $data->product_name = $request->product_name;
                $data->product_images = json_encode($Imgdata);
                $data->save();
 
            return redirect()->back()->with('success', "Product uploaded successfully.");
        }
    }

    public function list(){
        $imgdata = Multipleimageresizeupload::get();
        return view('resize_multiple_images_example.list',compact('imgdata'));

    }
}

Here we are resizing the image proportionally. Doing so, we keep the aspect ratio and the image. For example, we are passing width as 300 and height as 100. You can change these values as per your requirement.

Recommended Article: Image validation in Laravel 8.

resources\views\resize_multiple_images_example\create.blade.php

resize multiple images in Laravel using Intervention Image
<!DOCTYPE html>
<html>
   <head>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
      <style>
         a {
         color: #BE206B!important;
         }
         a.btn.btn-lg.btn-block,.btn-info {
         color: white !important;
         }
         .btn-secondary {
         background-color: #448BC6!important;
         color: #fff!important;
         }
         button.btn.btn.btn-secondary {
         width: 100%;
         }
         h3 {
         text-align: center;
         line-height: 200%;
         }
         .collpa
         .pt-0, .py-0 {
         padding-top: 0!important;
         }
      </style>
   </head>
   <main>
      <div class="container">
         <div class="col-sm-12 float-right">
               @if(Session::has('success'))
               <div class="alert alert-success alert-dismissible p-2">
                  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                  <strong>Success!</strong> {!! session('success')!!}.
               </div>
               @endif
            </div>
         <div class="row justify-content-center">

               @if ($errors->any())
                <div class="alert alert-danger">
                <ul>
                @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
                @endforeach
                </ul>
                </div><br/>
                @endif


            <div class="col-lg-6">
               <div class="main">
                  <h3><a>Upload and Resize Multiple Images in Laravel 8.</a></h3>
                  <form role="form" action="{{route('images.store')}}" method="post"enctype="multipart/form-data">
                     @csrf
                     <div class="form-group">
                        <label for="name">Product name<span class="text-danger">*</span></label>
                        <input type="text" name="product_name" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="images">Product Images<span class="text-danger">*</span></label>
                       <input type="file" class="form-control" name="product_imgs[]" accept="image/*" multiple />
                     </div>
                     <div class="form-group">
                     <button type="submit" class="btn btn btn-secondary">Upload</button>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
   </body>
</html>

Recommended Article: How to Display Session Flash Message in Laravel 8.

resources\views\resize_multiple_images_example\list.blade.php

resize multiple images in Laravel using Intervention Image package
<!DOCTYPE html>
<html lang="en">
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3><a>Upload and Resize Multiple Images in Laravel 8.</a></h3>
         <br>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Product name</th>
                  <th>Product Images</th>
               </tr>
            </thead>
            <tbody>
               @foreach($imgdata as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{ $data->product_name }}</td>
                  <td>
                  @foreach(json_decode($data->product_images, true) as $key => $media_imgs)
                  <a href="{{ url('storage/product_images/'.$media_imgs) }}"target="_blank">
                  <img src="{{ url('storage/product_images/'.$media_imgs) }}"class="img-fluid mb-2">
                  </a>
                  @endforeach
                  </td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>

Run Application :

127.0.0.1:8000/images-upload

Output :

laravel resize images

How to upload and resize multiple images in laravel 8?

upload and resize images before save in laravel

Read Also: How to Minify Html in Laravel 8.

In this article, we learned “upload and resize multiple images in laravel 8”, I hope this article will help you with your application Project.