How to Upload Multiple Image In Laravel 9 ?

Today now in this article, i will talk about the laravel 9 multiple image upload example. From this example i will help you about how to laravel 9 multiple images upload. This is a simple example about how we can upload multiple image in laravel 9. Here we will learn about laravel 9 multiple image upload also with the preview.

Here, i will install laravel 9 application and create a simple form with a file input field that we can use to select the multiple images. After submitting the form i will be store those images in the folder and database.

So, let’s start and follow the below step to create multiple images upload in the laravel 9 application example.

Step 1: Install Laravel 9

Now this step is not needed if you are already install previous; however, if you have not created the laravel application, then we may go ahead and execute the below command bellow:

composer create-project laravel/laravel example-app
Step 2: Create Migration and Model

Here, I will create the migration for the “images” table, let’s run the bellow command and also update code.

php artisan make:migration create_images_table

database/migrations/2022_02_10_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.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
};

Next, need to run to create new migration by using laravel migration command as bellow:

php artisan migrate

Now I will create a 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

Now in this step, i will create a new controller as name ImageController; in this file, I will add the two method index() and store() for the render view and store images into folder and also database logic.

So Let’s start and create ImageController by the following command:

php artisan make:controller ImageController

next, let’s update the following code on the Controller File.

app/Http/Controllers/ImageController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Image;
  
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('imageUpload');
    }
      
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'images' => 'required',
            'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
      
        $images = [];
        if ($request->images){
            foreach($request->images as $key => $image)
            {
                $imageName = time().rand(1,99).'.'.$image->extension();  
                $image->move(public_path('images'), $imageName);
  
                $images[]['name'] = $imageName;
            }
        }
  
        foreach ($images as $key => $image) {
            Image::create($image);
        }
      
        return back()
                ->with('success','You have successfully upload image.')
                ->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 and Add Routes

Now need to open the routes/web.php file and need to add the routes to manage GET and POST requests for the render view and also store image logic.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(ImageController::class)->group(function(){
    Route::get('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});
Step 5: Create Blade File

Now we are in last step here i need to create a blade file as name imageUpload.blade.php file and in this file i will create a form with file input button. So just copy the bellow and then put on that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Multiple Image Upload Example - CodingsPoint.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
      
<body>
<div class="container">
       
    <div class="panel panel-primary">
  
      <div class="panel-heading">
        <h2>Laravel 9 Multiple Image Upload Example - CodingsPoint.com</h2>
      </div>
  
      <div class="panel-body">
       
        @if ($message = Session::get('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
              <strong>{{ $message }}</strong>
              <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="300px">
            @endforeach
        @endif
      
        <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
            @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">Upload</button>
            </div>
       
        </form>
      
      </div>
    </div>
</div>
</body>
    
</html>

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →