How to upload images in Laravel 11 with preview

Diego Cortés
Diego Cortés
January 22, 2025
How to upload images in Laravel 11 with preview

Image management is a fundamental functionality in many web applications. Laravel 11 has further simplified this process, allowing developers to implement image uploads with preview effectively. Below, we present an informative guide on how to do it, based on best practices.

Prerequisites

Before you begin, make sure you have Laravel 11 installed and your development environment set up. It is essential to have a web server like Apache or Nginx and to have Composer installed. Additionally, it is advisable to have basic knowledge of PHP and Laravel.

Project Setup

To start, create a new project with the following command:

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

For this tutorial, we will use a MySQL database, so it will be necessary to configure the .env file of your project with the appropriate connection details.

Creating the Image Upload Form

The next step is to create a view where the image can be uploaded. Go to the resources/views folder and create a file named upload.blade.php. In this file, add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Images</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<h2>Upload an Image with Preview</h2>
<form id="image-form" enctype="multipart/form-data">
    @csrf
    <input type="file" id="image" name="image" accept="image/*" required>
    <br><br>
    <img id="preview" src="#" alt="Preview" style="display:none; width:200px; height:auto;" />
    <br><br>
    <button type="submit">Upload Image</button>
</form>

<script>
    $(document).ready(function() {
        $('#image').on('change', function() {
            const file = $(this)[0].files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#preview').attr('src', e.target.result);
                    $('#preview').show();
                }
                reader.readAsDataURL(file);
            }
        });
    });
</script>

</body>
</html>

This code creates a form that allows you to select an image, and upon selection, it instantly displays a preview.

Controller and Routes

Now, you need a controller to handle the image upload. Run the following command in the terminal to create a controller:

php artisan make:controller ImageController

In the new controller (ImageController.php), add the following method:

public function upload(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);

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

Now, define the route in routes/web.php to access the form and the upload method:

use App\Http\Controllers\ImageController;

Route::get('/upload', function () {
    return view('upload');
});

Route::post('/upload', [ImageController::class, 'upload']);

Conclusion

With these steps, you now have a basic system for uploading images with preview in Laravel 11. This functionality is very useful for various applications, allowing users to see their images before finalizing the upload.

I invite you to continue exploring more news and tutorials related on my blog, where you will find valuable information to enhance your skills as a developer. Don't miss it!

Article information

Published: January 22, 2025
Category: Laravel Tutorials
Reading time: 5-8 minutes
Difficulty: Intermediate

Key tips

1

Take your time to understand each concept before moving on to the next one.

2

Practice the examples in your own development environment for better understanding.

3

Don't hesitate to review the additional resources mentioned in the article.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Frequently Asked Questions

Categories

Page loaded in 29.22 ms