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 Image Upload With Preview Tutorial

Last Updated on April 14, 2024 by

In Laravel 11, an image upload with preview feature allows users to select an image file on the form and show its preview before submitting the form.

Let’s get started by following the steps below to create image upload with preview feature using jQuery:

Step 1 – Create Image Upload Form View

Create a preview-upload-form.blade.php file in the resources/views folder to allow users to select an image to preview before uploading images via the form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 Image Upload with Preview Tutorial - itcodStuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="mt-5">Laravel 11 Image Upload with Preview Tutorial - itcodStuff.com</h1>
        <form action="{{ url('upload-image') }}" method="post" enctype="multipart/form-data" class="mt-4">
            @csrf
            <div class="mb-3">
                <label for="image" class="form-label">Choose Image</label>
                <input type="file" class="form-control" id="image" name="image">
                <img id="preview" src="#" alt="Preview" style="display: none; max-width: 100%; margin-top: 10px;">
            </div>
            <button type="submit" class="btn btn-primary">Upload Image</button>
        </form>
    </div>

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

    <!-- Bootstrap JS (Optional, only if you need JavaScript features) -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#image').change(function() {
                previewImage(this);
            });
        });

        function previewImage(input) {
            var preview = $('#preview')[0];
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>

Step 2- Write jQuery Code to Show Preview

To show a preview of the image selected by the user before uploading it from the the form, you need to use the change event with jQuery fillReader() function on input file HTML element:

    <script>
        $(document).ready(function() {
            $('#image').change(function() {
                previewImage(this);
            });
        });

        function previewImage(input) {
            var preview = $('#preview')[0];
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>

Step 3- Handle Image Upload in Controller

Create a methods in controller file to handle image upload process:

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

class ImageController extends Controller
{
    public function index(Request $request)
    {
        return view('preview-upload-form');
    }
    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $imageName = time().'.'.$request->image->extension();  

        $request->image->move(public_path('images'), $imageName);

        $imagePath = 'images/' . $imageName;

        // Store image path in database if needed
        $image = new Image();
        $image->image_path = $imagePath;
        $image->save();

        return back()->with('success','Image uploaded successfully.');
    }
}

Step 4 – Define Routes

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

use App\Http\Controllers\ImagePreviewController;

Route::get('/preview-upload-form', [ImagePreviewController::class, 'index']);
Route::post('/upload-image', [ImagePreviewController::class, 'uploadImage']);

Step 5 – Test Application

Run application by using the following command:

php artisan serve

Now test your laravel 11 image upload application in browser:

http://127.0.0.1:8000/preview-upload-form

In the steps above, you have created a form with an HTML input file and used jquery fileReader() and Change event on the form that allows users to display a preview of image before upload and created a controller and route that handle image upload in Laravel 11.

Leave a Comment