Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Multiple Image Upload in Laravel 11 using Ajax

Last Updated on April 18, 2024 by

In Laravel 11, Ajax Multiple Image Upload allows users to upload multiple images at once without requiring page reloading with great user experience.

Steps to create ajax multiple image upload with preview:

Step 1 – Create Ajax Multiple Image Upload Form View

Create a form view and use jQuery AJAX to select multiple images and show a preview in it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Image Upload</title>
 <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <style>
        .preview-images-zone {
            width: 100%;
            border: 1px solid #ddd;
            min-height: 180px;
            border-radius: 5px;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            box-sizing: border-box;
        }
        .preview-image {
            width: 150px;
            height: 150px;
            margin: 10px;
            overflow: hidden;
            position: relative;
        }
        .preview-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h2>Multiple Image Upload with Preview</h2>
        <form id="uploadForm" action="{{ url('/upload/store') }}" method="post" enctype="multipart/form-data">
            @csrf
            <div class="input-group control-group increment">
                <input type="file" name="images[]" class="form-control" multiple>
            </div>
            <div class="preview-images-zone"></div>
            <button type="submit" class="btn btn-primary mt-3">Upload</button>
        </form>
    </div>

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

</body>
</html>

Step 2 – Write jQuery Ajax Code

Write jQuery AJAX code to send the image to the server and display its preview:

<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Ajax script -->
<script>
$(document).ready(function(){
    $('#imageUploadForm').on('submit', function(e){
        e.preventDefault();
        var formData = new FormData(this);
        
        $.ajax({
            type:'POST',
            url:"{{ route('upload') }}",
            data: formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                $('#preview').html(data);
            },
            error: function(xhr,status,error){
                console.log(xhr.responseText);
            }
        });
    });
});
</script>

Step 3 – Create Controller to Handle Ajax Multiple Image Upload

Create a methods in controller file by running the following command to handle ajax multiple image upload process:

php artisan make:controller MultipleUploadController

Step 4 – Define Methods in Controller

Define a methods in the controller file to handle ajax multiple image upload process with validation:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Image;

class MultipleUploadController extends Controller
{
    public function index()
    {
        return view('upload');
    }

public function upload(Request $request)
{
    if($request->hasFile('images')) {
        $images = $request->file('images');
        
        foreach($images as $image) {
            $imageName = time().'_'.$image->getClientOriginalName();
            $image->move(public_path('images'), $imageName);
            
            Image::create(['image_path' => 'images/'.$imageName]);
        }
        
        return 'Images uploaded successfully.';
    }
    
    return 'No images to upload.';
}
}

Step 5 – Add Routes

Add routes in web.php file to handle multiple image upload requests:

use App\Http\Controllers\ImageController;

Route::get('/', [ImageController::class, 'index']);
Route::post('upload', [ImageController::class, 'upload'])->name('upload');

Step 6 – Test Application

Run application by using the following command:

php artisan serve

Access the ajax multiple image upload form with preview in your browser (http://127.0.0.1:8000/upload):

http://127.0.0.1:8000/

Leave a Comment