Laravel 9 Multiple Image Upload Example

In this article, we will see the laravel 9 multiple image upload example. here, we will learn multiple image uploads in laravel 9. Uploading multiple images in laravel 9 is not a big task if you follow the below steps then you can very easily upload images with validation. 

Also, you can validate image mime type, image size, image dimension, etc on the laravel 9 controller by using laravel validation rules. you can see upload multiple images with a preview of image in laravel 9.

So, let's see multiple image uploads in laravel 9, laravel 9 multiple image uploads with a preview.

How To Upload Multiple Images In Laravel 9

Step 1: Install Laravel 9

Step 2: Add Model and Migration

Step 3: Create Controller

Step 4: Create Route

Step 5: Create Blade File

 

Step 1: Install Laravel 9

In this step, we will install a new laravel app(if required) for example how to upload multiple images in laravel 9.

composer create-project --prefer-dist laravel/laravel image_upload_example

 

 

Step 2: Add Model and Migration

Now, we will create a database, model, and migration for multiple image uploads.

php artisan make:model File -m

Now, edit the File model like below code example.

app/Models/File.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class File extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'file_names'
    ];
  
 
    public function setFilenamesAttribute($value)
    {
        $this->attributes['file_names'] = json_encode($value);
    }
}

Now, add the below code in the migration file.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateFilesTable extends Migration
{
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('file_names');
            $table->timestamps();
        });
    }
 
    public function down()
    {
        Schema::dropIfExists('files');
    }
}

Now, run migration with the artisan command in your terminal.

php artisan migrate

 

 

Step 3: Create Controller

Now, we will create FileController. and don't forget to create a "files" folder in your public directory to save your images.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\File;
  
class FileController extends Controller
{
    public function create()
    {
        return view('index');
    }
  
    public function store(Request $request)
    {
        $this->validate($request, [
                'file_names' => 'required',
                'file_names.*' => 'image'
        ]);
  
        $files = [];
        if($request->hasfile('file_names'))
         {
            foreach($request->file('file_names') as $file)
            {
                $name = time().rand(1,50).'.'.$file->extension();
                $file->move(public_path('files'), $name);  
                $files[] = $name;  
            }
         }
  
         $file= new File();
         $file->file_names = $files;
         $file->save();
  
        return back()->with('success', 'Images are successfully uploaded');
    }
}

 

Step 4: Create Route

In this step, we will create routes for multiple image uploads in laravel 9.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FileController;
  
  
Route::get('file', [FileController::class, 'create']); 
Route::post('file', [FileController::class, 'store']);

 

 

Step 5: Create Blade File

Now, we will create an index.blade.php file.

resources/views/index.blade.php.

<html lang="en">
<head>
  <title>Laravel 9 Multiple Image Upload Example - Techsolutionstuff</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  
<div class="container lst">
  
@if (count($errors) > 0)
<div class="alert alert-danger">
    <strong>Error!</strong> something went wrong <br><br>
    <ul>
      @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
      @endforeach
    </ul>
</div>
@endif
  
@if(session('success'))
<div class="alert alert-success">
  {{ session('success') }}
</div> 
@endif
  
<h3 class="well">Laravel 9 Multiple Image Upload Example - Techsolutionstuff</h3>
 
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
    @csrf
  
    <div class="input-group demo control-group lst increment" >
      <input type="file" name="file_names[]" class="myfrm form-control">
      <div class="input-group-btn"> 
        <button class="btn btn-success" type="button">Add</button>
      </div>
    </div>
    <div class="clone hide">
      <div class="demo control-group lst input-group" style="margin-top:10px">
        <input type="file" name="file_names[]" class="myfrm form-control">
        <div class="input-group-btn"> 
          <button class="btn btn-danger" type="button">Remove</button>
        </div>
      </div>
    </div>
  
    <button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
  
</form>        
</div>
  
<script type="text/javascript">
    $(document).ready(function() {
      $(".btn-success").click(function(){ 
          var lsthmtl = $(".clone").html();
          $(".increment").after(lsthmtl);
      });
      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".demo").remove();
      });
    });
</script>
  
</body>
</html>

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS