Laravel 10 Ajax Multiple Image Upload with Preview Example Tutorial

Laravel 10 Ajax Multiple Image Upload with Preview Example Tutorial

Upload multiple images using jQuery Ajax in laravel. In this tutorial, you will learn how to upload multiple images using jquery Ajax in Laravel 10 apps and show a preview of images before sending them to the server.

How to Upload Multiple Image with Preview Using Ajax in Laravel 10

Steps to upload multiple images using ajax with preview in Laravel 10 applications:

  • Step 1 – Install Laravel 10 Application
  • Step 2 – Configuration Database with App
  • Step 3 – Create Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Generate Controller using Artisan Command
  • Step 6 – Create an Ajax Form to Upload Multiple Image
  • Step 7 – jQuery Code To Show Multiple Image Preview
  • Step 8 – Write Ajax Code to Upload Multiple Image
  • Step 9 – Start Development Server

Step 1 – Install Laravel 10 Application

Firstly, open your command prompt to download or install Laravel 10 new setup. Execute the following commands into it to install the new Laravel 10 app on your system:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

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

Step 2 – Configuration Database with App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

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 this step, execute the following command on the command prompt or terminal to create photo migration and model file.

php artisan make:model Photo -m

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

  • blog/app/Models/Photo.php
  • blog/database/migrations/create_photos_table.php

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

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $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 this step, open your web.php file, so navigate inside routes directory. Then update the following routes into the web.php file:

use App\Http\Controllers\AjaxUploadMultipleImageController;

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

Route::post('upload-multiple-image-ajax', [AjaxUploadMultipleImageController::class, 'saveUpload']);

Step 5 – Create Controller using Artisan Command

In this step, execute the following artisan command to create a controller for showing the image upload form and storing images in the database:

php artisan make:controller AjaxUploadMultipleImageController

The above command will create the AjaxUploadMultipleImageController.php file, which is located inside blog/app/Http/Controllers/ directory.

So open the UploadImagesController.php file and add the following code to it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Photo;

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

    public function saveUpload(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;
                }
           }

            Photo::insert($insert);

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

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

    }   
        
}

Step 6 – Create an Ajax Form to Upload Multiple Image

In step, this, Go to the resources/views directory. And then create a new blade view file named multiple-image-upload-preview-ajax.blade.php inside this directory.

So, open this multiple-image-upload-preview-ajax.blade.php file in a text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 10 Multiple Image Upload AJAX With Preview - Tutsmake.com</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>
    .show-multiple-image-preview img
    {
          padding: 6px;
          max-width: 100px;
    }
  </style>

</head>
<body>

<div class="container mt-5">


    <h2 class="text-center">Laravel 10 Ajax Multiple Image Upload With Preview - Tutsmake.com</h2>

    <div class="text-center">

        <form id="multiple-image-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">
                        <input type="file" name="images[]" id="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="show-multiple-image-preview"> </div>
                    </div>  
                </div>
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </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 ShowMultipleImagePreview = 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() {
        ShowMultipleImagePreview(this, 'div.show-multiple-image-preview');
    });
  });    
  
   $('#multiple-image-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-multiple-image-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
           this.reset();
           alert('Images has been uploaded using jQuery ajax with preview');
           $('.show-multiple-image-preview').html("")
        },
        error: function(data){
           console.log(data);
         }
       });
   });
});

</script>
</body>
</html>

Step 7 – jQuery Code To Show Multiple Image Preview

In this step, implement the jQuery code to display or show multiple image previews before upload using Ajax in Laravel 10:

  $(function() {
    // Multiple images preview with JavaScript
    var ShowMultipleImagePreview = 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() {
        ShowMultipleImagePreview(this, 'div.show-multiple-image-preview');
    });
  }); 

Step 8 – Write Ajax Code to Upload Multiple Image

In this step, implement the jQuery and ajax code will upload multiple image on Laravel 10 controller file:

   $('#multiple-image-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-multiple-image-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
           this.reset();
           alert('Images has been uploaded using jQuery ajax with preview');
           $('.show-multiple-image-preview').html("")
        },
        error: function(data){
           console.log(data);
         }
       });
   });

Step 9 – Start Development Server

In this step, run the following command on cmd to start the development server:

php artisan serve

Then start this app on browser, so open your browser and fire the following URL into the browser:

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

Recommended Laravel Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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