Laravel 10/9 Ajax Multiple Image Upload with Preview

Laravel 10/9 multiple image upload ajax with preview; Through this tutorial, i am going to show you how to upload multiple image using jQuery ajax in Laravel 10/9 with show preview. And upload all images without refresh or reload the page.

In this post example, i will build jQuery bootstrap and ajax to create multiple image upload form in Laravel 10/9. And will display multiple image preview before upload to db and folder. As well as will validate multiple image mime type, size before upload/save to database and directory in Laravel 10/9.

Laravel 10/9 Ajax Multiple Image Upload with Preview

Follow the below given simple steps to upload multiple images in Laravel 10/9 app:

  • Step 1 – Install Laravel 10/9 Application
  • Step 2 – Database Configuration
  • Step 3 – Create Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Creating Ajax Upload Controller
  • Step 6 – Create Blade View
    • Create Ajax Multiple Image Upload Form
    • Implement Ajax Code to Upload Multiple Image
    • Implement jQuery Code to Show Image Preview
  • Step 7 – Start Development Server
  • Step 8 – Run This App On Browser

Step 1 – Install Laravel 10/9 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 latest application using the following command:

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

Step 2 – Database Configuration

In step 2, open your downloaded laravel 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 / LaravelMultipleImageUpload

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 multiple image upload with validation tutorial app, which is located inside the following locations:

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

So, find create_images_table.php file inside /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\AjaxUploadController;

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

Route::post('upload-images-ajax', [AjaxUploadController::class, 'store']);

Step 5 – Creating Ajax Upload Controller

In step 5, create multiple image upload ajax controller by using the following command:

php artisan make:controller AjaxUploadController

The above command will create AjaxUploadController.php file, which is located inside /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 AjaxUploadController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Image;

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

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

		if($request->TotalImages > 0)
		{
		       
		   for ($x = 0; $x < $request->TotalImages; $x++) 
		   {

		       if ($request->hasFile('images'.$x)) 
		        {
		            $file      = $request->file('images'.$x);

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

		            $insert[$x]['name'] = $name;
		            $insert[$x]['path'] = $path;
		        }
		   }

		    Image::insert($insert);

		    return response()->json(['success'=>'Multiple Image has been uploaded into db and storage directory']);

		 
		}
		else
		{
		   return response()->json(["message" => "Please try again."]);
		}

	}	
        
}

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 ajax-multiple-upload-image-preview.blade.php inside resources/views directory.

  • Create Ajax Multiple Image Upload Form
        <form id="multiple-image-upload-preview-ajax" method="POST"  action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <div class="input-group">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                        </div>
                        <div class="custom-file">
                          <input type="file" class="custom-file-input" id="images" name="images[]" multiple="">
                          <label class="custom-file-label" for="inputGroupFile01">Choose Multiple Images</label>
                        </div>
                      </div>
                    </div>
                </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>
  • Implement Ajax Code to Upload Multiple 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);
         }
       });
   });
  • Implement jQuery Code to Show Image Preview
  
  $(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');
    });
  }); 

The full source code of ajax-multiple-upload-image-preview.blade.php file is given below:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 10/9 Ajax Multiple Image Upload With Preview</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">

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 10/9 Upload Multiple Image with Preview Using Ajax</h2>
    </div>

    <div class="card-body">
        <form id="multiple-image-upload-preview-ajax" method="POST"  action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <div class="input-group">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                        </div>
                        <div class="custom-file">
                          <input type="file" class="custom-file-input" id="images" name="images[]" multiple="">
                          <label class="custom-file-label" for="inputGroupFile01">Choose Multiple Images</label>
                        </div>
                      </div>
                    </div>
                </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 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>
</body>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server:

php artisan serve

Step 8 – Run This App On Browser

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

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

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

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

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