Laravel 11 Multiple Image Upload Example

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
Laravel 11 Multiple Image Upload Example

Welcome To ITSolutionsGuides,


Lets see how to create multiple image upload example in laravel 11. In multple image upload we will use 'foreach' keyword to upload each and every image one by one. It is same as that of the single image upload difference is we will use the 'foreach' keyword to upload each of the image. In this Laravel 11 tutorial, we'll explore multiple image uploading.
Single Image Upload Example In Laravel 11

Let's Start Coding

Lets install the new laravel application using the following command,
laravel new multiple_image_example

Lets create both the model and the migration using the following artisan command,
php artisan make:model Image -m


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'
    ];
}

Let's Edit Migration

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');
    }
};

Let's Create Controller

Lets run the migrations using the following artisan command,
php artisan migrate

Then lets create the controller using the following artisan command,
php artisan make:controller ImageController
in the controller file we will use the foreach to upload each image seperately


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); 
    }
}

Let's Create Routes

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');

Let's Create Blade File

create blade file using artisan command

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Multiple Image Upload Example</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</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>

Let's Start Coding

Lets run the application using the following artisan command,

php artisan serve

http://localhost:8000/image-upload

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides