Laravel 9 Multiple Image Upload using jQuery Ajax Tutorial

In this tutorial, we will be showing you how to upload multiple images using jQuery ajax with previews in a Laravel 9 application. Before uploading these images, we will also be validating the image mime type, size, height, and width on the server-side.

Use the following step to upload multiple image using ajax with preview in laravel 9 applications:

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configure Database with App
  • Step 3 – Build Photo 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

Laravel 9 Ajax Multiple Image Upload with Preview Tutorial

Step 1: Install Laravel 9 Application
The first step is to install a fresh Laravel 9 application. You can do this by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel your-project-name

This will create a new Laravel 9 application in a directory named “your-project-name”.

Step 2: Configure Database with App
Next, you need to configure your database details in the “.env” file of your Laravel app. Open the “.env” file and update the following lines with your database details:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 3: Build Photo Model & Migration
Now, you need to create a Photo model and migration file. You can do this by running the following command in your terminal:

php artisan make:model Photo -m

This will create a new “Photo” model and a migration file for the “photos” table. Open the migration file and add the necessary code to create a “photos” table with the following columns:

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

Step 4: Create Routes
Next, you need to update your “web.php” file with the necessary routes for the multiple image preview and upload. Open the “web.php” file and add the following routes:

Route::get('/', [App\Http\Controllers\PhotoController::class, 'index']);
Route::post('/upload', [App\Http\Controllers\PhotoController::class, 'upload'])->name('upload');

Step 5: Generate Controller using Artisan Command
Now, you need to create a controller to handle the preview and upload of multiple images. You can do this by running the following command in your terminal:

php artisan make:controller PhotoController

This will create a new “PhotoController” file in the “app/Http/Controllers” directory. Open the controller file and add the necessary code to handle the preview and upload of multiple images.

Step 6: Create an Ajax Form to Upload Multiple Image
Create a new blade view file and add the necessary HTML and JavaScript code to display the form for uploading multiple images with previews. You can create a file named “upload.blade.php” in the “resources/views” directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Multiple Images with Preview in Laravel</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<div class="container mt-5">
    <h2>Upload Multiple Images with Preview in Laravel</h2>
    <hr>

    <form id="uploadForm" action="{{ route('upload') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label for="images">Choose Images</label>
            <input type="file" class="form-control-file" id="images" name="images[]" multiple>
            <div class="invalid-feedback"></div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-success">Upload</button>
        </div>
    </form>

    <div class="row mt-5">
        <div class="col-md-12">
            <div id="imagePreview"></div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // Preview Images Before Upload
        $('#images').on('change', function () {
            $('#imagePreview').html('');
            var files = $(this)[0].files;

            if (files.length > 0) {
                for (var i = 0; i < files.length; i++) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $('#imagePreview').append('<img src="' + e.target.result + '" class="img-thumbnail mr-2" width="200">');
                    }
                    reader.readAsDataURL(files[i]);
                }
            }
        });

        // Submit Form using Ajax
        $('#uploadForm').on('submit', function (e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    $('.btn-success').attr('disabled', true);
                    $('.invalid-feedback').html('');
                },
                success: function (response) {
                    if (response.status == 'success') {
                        alert(response.message);
                        $('#imagePreview').html('');
                        $('#uploadForm')[0].reset();
                    }
                },
                error: function (response) {
                    if (response.status == 422) {
                        var errors = $.parseJSON(response.responseText);
                        $.each(errors.errors, function (key, value) {
                            $('#' + key).addClass('is-invalid');
                            $('#' + key).siblings('.invalid-feedback').html(value);
                        });
                    }
                },
                complete: function () {
                    $('.btn-success').attr('disabled', false);
                }
            });
        });
    });
</script>

</body>
</html>

Step 7: jQuery Code To Show Multiple Image Preview
Add the necessary jQuery code to display the preview of multiple images before uploading. This code is already added in the “upload.blade.php” file.

Step 8: Write Ajax Code to Upload Multiple Image
Implement the jQuery and ajax code to upload the multiple images to the Laravel controller. This code is also already added in the “upload.blade.php” file.

Step 9: Start Development Server
Start the development server using the “php artisan serve” command and access the multiple image upload form through the browser by visiting “http://localhost:8000/”.

By following these steps, you can easily implement the feature of uploading multiple images with previews and validation in your Laravel 9 application.