Laravel 8 Upload Multiple Image with Preview

Laravel 8 multiple image upload with preview using jQuery example tutorial. In this post, i will share with you how to upload multiple image with preview and validation in laravel 8.

As well as you will learn how to upload multiple image in laravel 8. And show image preview before upload using jQuery.

In this example post, i will show multiple image preview before upload using jQuery library and validate image mime type, size and dimension, max size, etc on laravel controller file.

This laravel 8 upload multiple image with preview and validation app will look like in following images:

  • multiple image upload in laravel 8 with preview and validation
  • Show multiple image preview before upload

Laravel 8 Multiple Image Upload with Preview

Simple steps for laravel 8 upload multiple image with preview and validation:

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Create Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Creating Controller
  • Step 6 – Create Blade View
  • Step 7 – Start Development Server
  • Step 8 – Run Laravel 8 Multiple Image Upload with Preview App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelMultipleImageUploadPreview

Then create model and migration file by using the following command:

php artisan make:model Image -m

The above command will create two files into your laravel 8 multiple image upload with validation tutorial app, which is located inside the following locations:

  • LaravelMultipleImageUploadPreview/app/Models/Image.php
  • LaravelMultipleImageUploadPreview/database/migrations/create_images_table.php

So, find create_images_table.php file inside LaravelMultipleImageUploadPreview/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\UploadMultipleImagePreviewController;

Route::get('preview-upload-multiple-image', [UploadMultipleImagePreviewController::class, 'index']);

Route::post('store-images', [UploadMultipleImagePreviewController::class, 'store']);

Step 5 – Creating Controller

In step 5, create mutltiple image upload with preview controller by using the following command:

php artisan make:controller UploadMultipleImagePreviewController

The above command will create UploadMultipleImagePreviewController.php file, which is located inside LaravelMultipleImageUpload/app/Http/Controllers/ directory.

The following laravel validation rules will validate multiple image file before upload/save into database and storage directory:

     $validatedData = $request->validate([
	    'images' => 'required',
            'images.*' => 'mimes:jpg,png,jpeg,gif,svg'
        ]);

So open UploadMultipleImagePreviewController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Image;

class UploadMultipleImagePreviewController extends Controller
{
   public function index()
    {
        return view('preview-upload-multiple-image');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
	    'images' => 'required',
        'images.*' => 'mimes:jpg,png,jpeg,gif,svg'
        ]);


        if($request->hasfile('images'))
         {
            foreach($request->file('images') as $key => $file)
            {
                $path = $file->store('public/images');
                $name = $file->getClientOriginalName();

                $insert[$key]['name'] = $name;
                $insert[$key]['path'] = $path;

            }
         }

        Image::insert($insert);

        return redirect('upload-multiple-image')->with('status', 'Multiple Image has been uploaded into db and storage directory');

    }
}

The following code will upload multiple image inside storage/app/public/images directory:

  $path = $file->store('public/images');        

Step 6 – Create Blade Views

In step 6, create new blade view file that named preview-multiple-image-upload.blade.php inside resources/views directory for upload multiple image form.

I have already created multiple image upload form in laravel, so you can add the following code into preview-multiple-image-upload.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>How to Upload Multiple Image with Preview and Validation In Laravel 8</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">


   <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <style>
    .preview-image img
    {
          padding: 10px;
          max-width: 100px;
    }
  </style>

</head>
<body>

<div class="container mt-5">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 8 Upload Multiple Image With Preview and Validation</h2>
    </div>

    <div class="card-body">
        <form name="upload-multiple-image" method="POST"  action="{{ url('store-images') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="images[]" placeholder="Choose images" multiple >
                    </div>
                    @error('images')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>

                
                <div class="col-md-12">
                    <div class="mt-1 text-center">
                        <div class="preview-image"> </div>
                    </div>  
                </div>
                  
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div> 

<script>  $(function() {
    // Multiple images preview with JavaScript
    var multiImgPreview = function(input, imgPreviewPlaceholder) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#images').on('change', function() {
        multiImgPreview(this, 'div.preview-image');
    });
  });  </script> 
</body>
</html>

The following code display error message on laravel multiple image upload forms. So do not forget to add the following code along laravel forms fields:

          @error('images')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

And the following javascript code will show multiple images preview before upload to database and directory:

<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
  
  $(function() {
    // Multiple images preview with JavaScript
    var multiImgPreview = function(input, imgPreviewPlaceholder) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#images').on('change', function() {
        multiImgPreview(this, 'div.preview-image');
    });
  });    
  
   $('#multiple-image-upload-preview-ajax').submit(function(e) {

     e.preventDefault();
  
      var formData = new FormData(this);

      let TotalImages = $('#images')[0].files.length; //Total Images
      let images = $('#images')[0];
      for (let i = 0; i < TotalImages; i++) {
          formData.append('images' + i, images.files[i]);
      }
      formData.append('TotalImages', TotalImages);
  
     $.ajax({
        type:'POST',
        url: "{{ url('upload-images-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
           this.reset();
           alert('Multiple Images has been uploaded using jQuery ajax with preview');
           $('.preview-image').html("")
        },
        error: function(data){
           console.log(data);
         }
       });
   });
});

</script>

Don’t worry i have already added the validation error message display code along with each form fields. And show multiple images preview jQuery code.

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel 8 image upload application:

php artisan serve

Step 8 – Run Laravel 8 Multiple Image Upload with Preview App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/preview-upload-multiple-image

Note that, in this example, the multiple images will be upload on the following path – storage/app/public/images.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *