Milind Daraniya

Laravel 10 Ajax Image Upload Preview Example

Published September 10th, 2023 20 min read

Implementing image upload functionality with preview using Ajax in a Laravel application is a seamless way to enhance the user experience. In this example, we'll demonstrate how to create an Ajax-based image upload preview feature in Laravel 10.

Step 1: Set Up the Laravel Project

Create a new Laravel 10 project using Composer:

composer create-project laravel/laravel image-upload-preview-example
cd image-upload-preview-example

Step 2: Create a Controller and Routes

Create a new controller that handles the image upload and preview:

php artisan make:controller ImageUploadController

In the generated ImageUploadController.php file, implement the methods to handle image upload and preview:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageUploadController extends Controller
{
    public function index()
    {
        return view('image-upload');
    }

    public function upload(Request $request)
    {
        $image = $request->file('image');
        $imageName = time() . '.' . $image->extension();
        $image->move(public_path('uploads'), $imageName);

        return response()->json(['image_url' => asset('uploads/' . $imageName)]);
    }
}

Define the routes in routes/web.php:

use App\Http\Controllers\ImageUploadController;

Route::get('/image-upload', [ImageUploadController::class, 'index']);
Route::post('/upload', [ImageUploadController::class, 'upload']);

Step 3: Create the View

Create a view file named image-upload.blade.php in the resources/views directory:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Ajax Image Upload Preview</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Laravel 10 Ajax Image Upload Preview</h1>
    <form id="imageUploadForm" method="post" enctype="multipart/form-data">
        @csrf
        <input type="file" name="image" id="imageInput" accept="image/*">
        <button type="submit">Upload</button>
    </form>
    <div id="imagePreview"></div>

    <script>
        $(document).ready(function() {
            $('#imageUploadForm').submit(function(event) {
                event.preventDefault();
                var formData = new FormData(this);

                $.ajax({
                    url: '/upload',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        var imageUrl = response.image_url;
                        $('#imagePreview').html('<img src="' + imageUrl + '" alt="Preview">');
                        $('#imageInput').val('');
                    }
                });
            });
        });
    </script>
</body>
</html>

Step 4: Create an "uploads" Directory

Create an "uploads" directory in the public folder to store the uploaded images:

mkdir public/uploads

Step 5: Start the Development Server

Start the Laravel development server and access the application in your web browser:

php artisan serve

Visit http://127.0.0.1:8000/image-upload in your browser to access the image upload page. Choose an image to upload, and it will be displayed as a preview below the upload button.