How to Upload Multiple Images in Laravel 9?

Published On: 11/06/2022 | Category: Laravel Laravel 9

Hi Dev,

Now, let's see article of How to Upload Multiple Images in Laravel 9?. I would like to show you Laravel 9 Multiple Image Upload with Preview. if you have question about Laravel 9 Multiple Image Upload Tutorial then I will give simple example with solution. This article goes in detailed on Upload Multiple Images in Laravel 9 with Validation. Let's get started with How to do validation for multiple images upload in laravel 9.

This article will give you simple example of How to Validate & Upload Multiple Image in Laravel 9?

Let's start following example:

Step 1: Install Laravel

First of all we are going from scratch new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2 : Create New Migration
php artisan make:migration create_images_table
database/migrations/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.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
};

php artisan migrate
Step 3 : Create New Model
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 = [
        'image',
    ];
}
Step 4 : Create New Controller

In this second step, we need to create a new MultipleImageController; in this file, we will add two method index() and store() for render view and store image logic.

Let's create MultipleImageController by following command:

php artisan make:controller MultipleImageController
app/Http/Controllers/MultipleImageController.php
<?php

namespace App\Http\Controllers;

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

class MultipleImageController extends Controller
{
    /**
     * Write Your Code..
     *
     * @return string
    */
    public function index()
    {
        return view('index');
    }

    /**
     * Write Your Code..
     *
     * @return string
    */
    public function store(Request $request)
    {
        $request->validate([
            'images' => 'required',
            'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        if ($request->images){
            foreach($request->images as $key => $image)
            {
                $imageName = $image->getClientOriginalName();  
                $image->move(public_path('images'), $imageName);

                $images[]['name'] = $imageName;
                Image::create([
                    'image' => $imageName
                  ]);
            }
        }

        return back()->with('success','You have successfully upload images.')->with('images', $images);
    }
}

Step 5 : Create Routes routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MultipleImageController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/multipleImage',[MultipleMultipleImageController::class, 'index']);
Route::post('multipleImage-store',[MultipleMultipleImageController::class, 'store'])->name('multipleImage.store');
Step 6: Create Blade File resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Upload Multiple Images in Laravel 9? - Tuts-Station.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    
    <style type="text/css">
        #previewImage
        {
            border: 1px solid black;
            margin-bottom: 5px;
        }
    </style>
    
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h1 class="text-center">How to Upload Multiple Images in Laravel 9? - Tuts-Station.com</h1>
                    </div>
                    <div class="card-body">
                        
                        @if ($message = Session::get('success'))
                            <div class="alert alert-success alert-dismissible fade show mb-2" role="alert">
                                {{ $message }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                            
                            @foreach(Session::get('images') as $image)
                                <img src="images/{{ $image['name'] }}" width="100px" height="100px" id="previewImage">
                            @endforeach
                        
                        @endif


                        <form action="{{ route('multipleImage.store') }}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="mt-3">
                                <label>Select Image<span class="text-danger">*</span></label>
                                <input type="file" name="images[]" class="form-control @error('images') is-invalid @enderror"  multiple>

                                @error('images.*')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                                @error('images')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="text-center mt-3">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                        </form>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Run Laravel App:

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

php artisan serve
Output :

I hope it can help you...