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.

Laravel 11 Ajax Image Upload Tutorial

Last Updated on April 17, 2024 by

In Laravel 11, AJAX allows image uploading without page refresh and jQuery allow displaying a preview of the image before send it to server.

Let’s start by creating AJAX image upload functionality, which allows users to select an image in the form, click the upload button, and see a preview of the uploaded image without reloading the page.

Step 1: Create Image Upload Form

Create a view file (e.g., resources/views/upload.blade.php) to include an input field for selecting the image and a container to display the uploaded image preview:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 AJAX Image Upload Tutorial - itcodStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h2 class="text-center mb-4">Laravel 11 AJAX Image Upload Tutorial - itcodStuff.com</h2>
                <form id="uploadForm">
                    <div class="mb-3">
                        <input type="file" class="form-control" id="imageInput" name="image">
                    </div>
                    <button type="button" id="uploadBtn" class="btn btn-primary">Upload</button>
                </form>
                <div id="previewContainer" class="mt-4"></div>
            </div>
        </div>
    </div>


</body>
</html>

Step 2: Use Ajax function to Upload Image

Edit resources/views/upload.blade.php file to add jQuery AJAX code to upload images with a preview without refreshing the page.

    <script>
        $(document).ready(function() {
            $('#uploadBtn').on('click', function() {
                var formData = new FormData();
                formData.append('image', $('#imageInput')[0].files[0]);

                $.ajax({
                    url: '{{ route("upload.image") }}',
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        // Handle success response
                        $('#previewContainer').html('<img src="' + response.url + '" class="img-fluid">');
                    },
                    error: function(xhr, status, error) {
                        // Handle error response
                        console.error(xhr.responseText);
                    }
                });
            });
        });
    </script>

Step 3: Create Controller

Generate a controller named AjaxUploadController by using the following command:

php artisan make:controller AjaxUploadController

Edit AjaxUploadController.php and define methods in it to handle the AJAX request for image upload:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Image;

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

    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust max file size as needed
        ]);

        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('public/images');
            $imageUrl = Storage::url($imagePath);

            return response()->json(['url' => $imageUrl]);
        }

        return response()->json(['error' => 'Image upload failed.']);
    }

}

Step 4 – Define Routes

Define a route to handle the AJAX request in your routes/web.php file:

use App\Http\Controllers\AjaxUploadController;

Route::get('/upload', [AjaxUploadController::class, 'index']);
Route::post('/upload/image', [AjaxUploadController::class, 'uploadImage'])->name('upload.image');

Step 5: Test Your Application

Run your Laravel server:

php artisan serve

Hit http://localhost:8000/upload in your browser and test the AJAX image upload functionality in laravel 11 applications.

Leave a Comment