How to Upload Image in Laravel: Complete Tutorial

how to upload image in laravel

The image upload feature is a must-have for websites, enabling functionalities like user profiles and product galleries. In a Laravel website, this feature boosts user engagement and enriches content presentation, making your website more interactive and visually appealing.

In this blog, we’ll walk you through the essentials of uploading images in Laravel. We’ll discuss supported image formats, how to add upload single and multiple images functionality in Laravel. Additionally, we’ll learn alternative ways used by Laravel development experts to implement upload images functionality. With that said, let’s dive in!

What Image Format Laravel Supports?

Before diving into the upload process, let’s understand the image formats Laravel can handle. These formats determine how images are stored and displayed, impacting factors like file size and quality.

  • Common Web Formats. Laravel seamlessly supports popular web formats like JPEG (.jpg), PNG (.png), and GIF (.gif). These formats offer a good balance between image quality and file size, making them ideal for various web applications.
  • Modern Options. Laravel also welcomes modern image formats like WebP (.webp). WebP offers superior compression compared to JPEG, resulting in smaller file sizes while maintaining good image quality. However, browser compatibility for WebP is still under development, so consider offering fallback options.
  • Scalable Vector Graphics (SVG). For logos or icons that require sharp scaling across different screen sizes, Laravel supports SVG format. SVGs are vector-based graphics, meaning they can be resized without losing quality.

With this knowledge in hand, you’re well-equipped to choose the right image format for your Laravel project’s specific needs. Now, let’s move on to the steps you are here for; upload an image in Laravel.

How to Upload Single Image in Laravel?

Uploading and displaying images is a common requirement in Laravel applications. In this guide, we’ll walk you through the complete process of uploading a single image and displaying it in Laravel 11, including setting up the upload form and showing the uploaded images dynamically.

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Laravel 11 Installed: If you haven’t installed Laravel 11, you can do so by running the following commands:
composer create-project laravel/laravel example-app
cd example-app

Once these prerequisites are ready, let’s begin with the steps to upload and display images.

Step 1: Set Up the Directory for Image Storage

Images will be stored in the public/uploads directory. Laravel will automatically create this folder when you upload an image, but you need to ensure that the public/ directory is writable.

Step 2: Create the Controller

Create a controller that will handle the image upload and display logic:

php artisan make:controller ImageUploadController

This will create a new ImageUploadController.php file in the app/Http/Controllers directory.

Step 3: Define Routes

Next, define the routes for the upload form, image upload handling, and displaying uploaded images. Open routes/web.php and add the following routes:

use App\Http\Controllers\ImageUploadController;
Route::get('/upload', [ImageUploadController::class, 'showForm'])->name('image.form');
Route::post('/upload', [ImageUploadController::class, 'upload'])->name('image.upload');
Route::get('/images', [ImageUploadController::class, 'listImages'])->name('images.list');

These routes will handle:

  • Displaying the upload form (GET /upload).
  • Handling image uploads (POST /upload).
  • Listing all uploaded images (GET /images).

Step 4: Implement Controller Logic

Now, implement the controller logic in the ImageUploadController.php file.

Code: Display the Upload Form

public function showForm()
{
    return view('upload');
}

Code: Handle Image Uploads

use Illuminate\Http\Request;
public function upload(Request $request)
{
    // Validate the image
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);
    // Create the uploads directory if it doesn't exist
    $uploadPath = public_path('uploads');
    if (!file_exists($uploadPath)) {
        mkdir($uploadPath, 0755, true);
    }
    // Store the image
    if ($request->file('image')) {
        $imageName = time() . '.' . $request->image->extension();
        $request->image->move($uploadPath, $imageName);

        return redirect()->route('image.form')
            ->with('success', 'Image uploaded successfully!')
            ->with('image', $imageName);
    }
    return redirect()->route('image.form')->with('error', 'Image upload failed.');
}

Code: Display All Uploaded Images

public function listImages()
{
    $images = glob(public_path('uploads/*.*')); // Retrieve all files in the uploads directory
    $images = array_map(function ($image) {
        return asset('uploads/' . basename($image)); // Convert file paths to URLs
    }, $images);
    return view('images', compact('images'));
}

Step 5: Create Blade Templates

There are various pages for which you need to create the Blade templates. Here is the code for each of the required blade templates:

Code: Upload Form (resources/views/upload.blade.php)

Here’s a simple and responsive image upload form:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Image Upload</title>
   <style>
       /* Styling for form */
       /* Add styles for better design */
   </style>
</head>
<body>
   <div class="container">
       <h1>Upload an Image</h1>
       @if(session('success'))
           <div class="success">
               {{ session('success') }}
           </div>
           <img src="{{ asset('uploads/' . session('image')) }}" alt="Uploaded Image">
       @endif
       @if(session('error'))
           <div class="error">
               {{ session('error') }}
           </div>
       @endif
       <form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data">
           @csrf
           <label for="image">Choose an Image:</label>
           <input type="file" name="image" id="image" required>
           <button type="submit">Upload</button>
       </form>
       <a href="{{ route('images.list') }}">View All Uploaded Images</a>
   </div>
</body>
</html>

Code: Images List (resources/views/images.blade.php)

This page will display all uploaded images in a responsive grid:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Uploaded Images</title>
   <style>
       /* Styling for gallery */
       /* Add responsive grid and hover effects */
   </style>
</head>
<body>
   <div class="container">
       <h1>Uploaded Images</h1>
       @if(count($images) > 0)
           <div class="gallery">
               @foreach($images as $image)
                   <img src="{{ $image }}" alt="Uploaded Image">
               @endforeach
           </div>
       @else
           <p>No images uploaded yet.</p>
       @endif
       <a href="{{ route('image.form') }}">Upload Another Image</a>
   </div>
</body>
</html>

Step 6: Test the Application

Once everything is set up, you can visit the /upload route to upload images. After uploading, you can view the uploaded image on the same page. To see all uploaded images, go to the /images route, where they will be displayed in a grid layout. Here is the kind of output you will see:

choosing image to upload in Laravel

Now, you may click on the “Choose file” button and upload the images. Once you add the images you will be displayed with the images as below:

uploaded image display

With that, we have successfully built an image upload and display system in Laravel 11. This system allows users to upload images, view success/error messages, and browse all uploaded images in a gallery. You can further customize and extend this functionality to suit your application’s needs.

Struggling to build a Laravel website with interactive features?

How to Upload Multiple Images in Laravel?

We have seen how to upload a single image in Laravel, now let’s dive into how to upload multiple images. So, let’s dive into the process!

Step 1: Create the Controller

The first step is to create a controller to handle the image upload logic, display the form, and list the uploaded images. Run the following command to create the MultipleImageUploadController:

php artisan make:controller MultipleImageUploadController

Once the controller is created, open the file located at app/Http/Controllers/MultipleImageUploadController.php and add the following methods:

  • showForm: Displays the upload form.
  • upload: Handles the image upload process.
  • listImages: Retrieves and displays the list of uploaded images.

Here’s the code to add to your controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class MultipleImageUploadController extends Controller
{
    // Show the form to upload multiple images
    public function showForm()
    {
        return view('multi-upload');
    }
    // Handle the image upload
    public function upload(Request $request)
    {
        $request->validate([
            'images.*' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Validation for each image
        ]);
        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $image->store('uploads/multiple', 'public'); // Store in 'public' disk
            }
        }
        return redirect()->route('multi.image.form')->with('success', 'Images uploaded successfully!');
    }
    // Show all uploaded images
    public function listImages()
    {
        $images = Storage::disk('public')->files('uploads/multiple');
        return view('multi-images', ['images' => $images]);
    }
}

Step 2: Define the Routes

Next, define the routes to handle the form display, image upload, and viewing uploaded images. Add these routes to routes/web.php:

use App\Http\Controllers\MultipleImageUploadController;
Route::get('/multi-upload', [MultipleImageUploadController::class, 'showForm'])->name('multi.image.form');
Route::post('/multi-upload', [MultipleImageUploadController::class, 'upload'])->name('multi.image.upload');
Route::get('/multi-images', [MultipleImageUploadController::class, 'listImages'])->name('multi.images.list');

Here’s what each route does:

  • GET /multi-upload: Displays the form for uploading images.
  • POST /multi-upload: Handles the upload process.
  • GET /multi-images: Displays the list of uploaded images.

Step 3: Create the Upload Form View

You need two Blade views: one for the upload form and another to display the uploaded images. First, let’s create the blade view for upload form. It displays a simple form for users to upload multiple images. Save the following code in resources/views/multi-upload.blade.php:

<!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>
    <style>
        /* Add your styling here */
    </style>
</head>
<body>
    <div class="container">
        <h1>Upload Multiple Images</h1>
        @if(session('success'))
            <div class="success">{{ session('success') }}</div>
        @endif
        <form action="{{ route('multi.image.upload') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <label for="images">Choose Images:</label>
            <input type="file" name="images[]" id="images" multiple required>
            <button type="submit">Upload</button>
        </form>
        <a href="{{ route('multi.images.list') }}">View Uploaded Images</a>
    </div>
</body>
</html>

Step 4: Create the Gallery View

This view displays all the uploaded images in a grid layout. Save the following code in resources/views/multi-images.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Uploaded Images</title>
    <style>
        /* Add your styling here */
    </style>
</head>
<body>
    <div class="container">
        <h1>Uploaded Images</h1>
        @if(count($images) > 0)
            <div class="gallery">
                @foreach($images as $image)
                    <img src="{{ asset('storage/' . $image) }}" alt="Uploaded Image">
                @endforeach
            </div>
        @else
            <p>No images uploaded yet.</p>
        @endif
        <a href="{{ route('multi.image.form') }}">Upload More Images</a>
    </div>
</body>
</html>

Step 5: Final Adjustments

Ensure the public directory has write permissions. Here is how you can set them:

chmod -R 775 storage
chmod -R 775 public/storage

Plus, if you haven’t already, create a symlink for public storage by running:

php artisan storage:link

Step 6: Test the Setup

Once everything is in place, navigate to /multi-upload to upload images. Here is the kind of interface you will see on your screen:

choosing multiple images to upload in Laravel

After successful upload, click the link to view uploaded images in /multi-images, there you will see all the uploaded images:

multiple image display

With this setup, you now have a functional multiple image upload feature in your Laravel application. Feel free to enhance it with additional features like image deletion or adding advanced validation. If you are looking to build a site that is interactive and robust, get in touch with our Laravel development company.

Alternate Ways to Implement Image Upload in Laravel

Laravel provides multiple methods to implement image upload, catering to diverse use cases and preferences. Here are some alternate approaches for achieving this functionality effectively:

Using Laravel’s Built-in File Upload (No Package)

Laravel’s built-in file upload system allows seamless handling of single images using methods like store() or storeAs(). Here are the steps to do so:

  • Create a form with enctype=”multipart/form-data”.
  • Access the uploaded file using the Request object.
  • Store the file in the desired directory (e.g., public, local, or a custom disk).
  • Optionally validate the file for image type and size.

Uploading multiple images follows a similar process but involves iterating through the uploaded files. To upload multiple images:

  • Use a form input that allows multiple file selection (<input type=”file” name=”images[]” multiple>).
  • Loop through the uploaded files in the controller using foreach and store them individually.
  • Return a success message after all files are uploaded.

Using the Intervention Image Package

Intervention Image is a versatile library that provides advanced image manipulation features like resizing and cropping during the upload process. Here is the composer command you can use to install the package:

composer require intervention/image

After that, configure the package, validate and manipulate the image (e.g., resize) before storage. Here is the example code to use image intervention package:

use Intervention\Image\Facades\Image;
public function upload(Request $request)
{
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);
    $image = $request->file('image');
    $imageName = time() . '.' . $image->getClientOriginalExtension();
    // Resize the image
    $img = Image::make($image)->resize(300, 200);
    $img->save(public_path('uploads/images/' . $imageName));
}

Using Livewire for Image Upload

Livewire simplifies the process of building dynamic interfaces in Laravel, including image uploads, without requiring full-page reloads. Here is the composer command you can use to get livewire in your project:

composer require livewire/livewire

Once it is required, create a component for file uploads and use Livewire’s support for handling file uploads seamlessly. Here is the code for using Livewire for image upload:

use Livewire\Component;
class ImageUpload extends Component
{
    public $image;
    public function uploadImage()
    {
        $this->validate([
            'image' => 'image|max:2048',
        ]);
        $imageName = time() . '.' . $this->image->getClientOriginalExtension();
        $this->image->storeAs('images', $imageName, 'public');
        session()->flash('message', 'Image uploaded successfully!');
    }
    public function render()
    {
        return view('livewire.image-upload');
    }
}

Each method offers unique advantages depending on your project’s requirements. Whether using Laravel’s built-in features, the Intervention Image package, or the dynamic capabilities of Livewire, you can implement image uploads customized to your needs.

Build your dream Laravel application with us!

FAQs About How to Upload Image in Laravel

How to store an image in storage in Laravel?
To store an image in Laravel's storage, use the store() or storeAs() method on the uploaded file. For example, $image->store('images', 'public'); saves the file in the storage/app/public/images directory. Ensure you configure the storage link using php artisan storage:link for public access.
How do I upload the image in Laravel?
For uploading an image in Laravel, create a form with enctype="multipart/form-data" and handle the uploaded file in your controller using the Request object. Validate the file, save it using store() or storeAs() methods, and optionally process it with tools like Intervention Image.
How to display an image in Laravel?
You can display an image in Laravel by ensuring the image is stored in the public directory or accessed via a proper URL. Once stored, you can reference the image by its URL in your application, and Laravel will serve it like any other static asset. Just place the image in the right folder and use the correct URL in your views or templates.

Wrapping Up

Uploading images in Laravel is a straightforward process, thanks to its built-in tools and functionalities. By following the steps outlined in this guide—creating a form, setting up routes and writing the controller logic you can easily integrate image uploads into your Laravel project.

With these basics covered, you can now enhance your application further, like adding validation, resizing images, or even implementing file management systems. Plus, you can use alternate methods like, using Livewire form implementing image upload functionality on your website.

If you need advanced functionalities for your Laravel app, consider hiring professional Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment