Laravel 11 Multiple Image Upload Tutorial Example

By Hardik Savani April 16, 2024 Category : Laravel

Hi, In this tutorial, I would like to share with you how to upload multiple images in laravel 11 application.

In this example, we'll create an "images" table with a "name" column. Then, we'll design a simple web page where users can select multiple images to upload. We'll save these images both to the "images" folder and the database.

Step for Laravel 11 Multiple Image Upload Example

  • Step 1: Install Laravel 11
  • Step 2: Create Migration and Model
  • Step 3: Create Controller
  • Step 4: Create Routes
  • Step 5: Create Blade File
  • Run Laravel App

So, let's follow the steps below to create multiple image uploads in the Laravel 11 application example.

laravel 11 multiple images upload

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Migration and Model

Here, we will create a migration for the "images" table. Let's run the below command and update the code.

php artisan make:migration create_images_table

database/migrations/2022_03_13_140040_create_images_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('images');
    }
};

Next, run the create new migration using Laravel migration command as below:

php artisan migrate

Now we will create the Image model by using the following command:

php artisan make:model Image

app/Models/Image.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Image extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name'
    ];
}

Step 3: Create Controller

In this step, we will create a new `ImageController`. In this file, we will add two methods: `index()` and `store()`, for rendering views and storing images into a folder and implementing database logic.

Let's create the `ImageController` by using the following command:

php artisan make:controller ImageController

Next, let's update the following code to the Controller file.

app/Http/Controllers/ImageController.php

<?php
      
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\Image;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
    
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('imageUpload');
    }
         
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        // Validate incoming request data
        $request->validate([
            'images' => 'required|array',
            'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        // Initialize an array to store image information
        $images = [];
  
        // Process each uploaded image
        foreach($request->file('images') as $image) {
            // Generate a unique name for the image
            $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
              
            // Move the image to the desired location
            $image->move(public_path('images'), $imageName);
  
            // Add image information to the array
            $images[] = ['name' => $imageName];
        }
  
        // Store images in the database using create method
        foreach ($images as $imageData) {
            Image::create($imageData);
        }
          
        return back()->with('success', 'Images uploaded successfully!')
                     ->with('images', $images); 
    }
}

Store Images in Storage Folder


$image->storeAs('images', $imageName);
  
// storage/app/images/file.png

Store Images in Public Folder


$image->move(public_path('images'), $imageName);
  
// public/images/file.png

Store Images in S3


$image->storeAs('images', $imageName, 's3');

Step 4: Create Routes

Furthermore, open `routes/web.php` file and add the routes to manage GET and POST requests for rendering views and storing image logic.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

Step 5: Create Blade File

At the last step, we need to create an "imageUpload.blade.php" file. In this file, we will create a form with a file input button. So, copy the code below and paste it into that file.

resources/views/imageUpload.blade.php


<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Multiple Image Upload Example - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Multiple Image Upload Example - ItSolutionStuff.com</h3>
        <div class="card-body">
  
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
                @foreach(Session::get('images') as $image)
                    <img src="images/{{ $image['name'] }}" width="300px">
                @endforeach
            @endsession
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data" class="mt-2">
                @csrf
       
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Select Images:</label>
                    <input 
                        type="file" 
                        name="images[]" 
                        id="inputImage"
                        multiple 
                        class="form-control @error('images') is-invalid @enderror">
      
                    @error('images')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
      
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/image-upload

Output:

laravel 11 multiple image output

I hope it can help you...

Shares