Laravel 8 Upload Multiple Images Tutorial

By : phpicoder Created : February 25, 2021

Hello Developer, In this tutorial, we will learn how to upload multiple images in laravel 8 tutorial, we will mack example laravel 8 multiple images upload, this example will help you upload multiple images in laravel 8 web applications, So we will look and esy mack laravel 8 multiple image upload tutorial.

I will create a simple example for uploading multiple images in the Laravel 8 application. So you can basically use this code on your Laravel 8 project.

If you are looking for how to upload multiple images to Laravel 8, if yes you are in the right place. to follow my code step by step.

So here you have to just follow bellow step to create Laravel 8 upload multiple File with Validation Example.

Preview: "upload multiple images in laravel"
Laravel 8 Upload Multiple Images Tutorial

Step 1: Install Laravel  App

open command prompt and run below command to install latest laravel application.

composer create-project --prefer-dist laravel/laravel multiple-images-upload

Step 2: Create Database Table

Now go to over project folder name multiple-images-upload and run below command to create migration

php artisan make:migration create_sliders_table

Now go to database/migrations folder and edit CreateSlidersTable file for following below code

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

Follow the command below the code to automatically create a database sliders table

php artisan migrate

Step 3: Create model file

Now we will create Slider model by using following command: 

php artisan make:model slider

app/Models/Slider.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Slider extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'imageName'
    ];
  
    /**
     * Set the user's first name.
     *
     * @param  string  $value
     * @return void
     */
    public function setFilenamesAttribute($value)
    {
        $this->attributes['imageName'] = json_encode($value);
    }
}

Step 4: Create Routes

Now, we will create routes for multiple file upload. so create two route (1)create (2)store 

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\SliderController;
  
/*
|--------------------------------------------------------------------------
| 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('slider', [SliderController::class, 'create'])->name('slider_create'); 
Route::post('slider', [SliderController::class, 'store'])->name('slider_store');

Step 5: Create Controller

Now go to app/Http/Controllers/ and create new Controller name SliderController.php and then following below code 

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Slider;
  
class SliderController extends Controller
{
    public function create()
    {
        return view('create');
    }
  
    public function store(Request $request)
    {
        $this->validate($request, [
                'imageName' => 'required',
                'imageName.*' => 'image'
        ]);
  
        $sliderImages = [];
        if($request->hasfile('imageName'))
         {
            foreach($request->file('imageName') as $img)
            {
                $name = time().rand(1,100).'.'.$img->extension();
                $img->move(public_path('slides'), $name);  
                $sliderImages[] = $name;  
            }
         }
  
         $slider= new Slider();
         $slider->imageName = $sliderImages;
         $slider->save();
  
        return back()->with('success', 'Slider images added hase been successfully');
    }
}

Store Image in Public Folder

$file->move(public_path('slides'), $name);
// public/slides/123456.png

Store Image in Storage Folder

$img->storeAs('slides', $name);
// storage/app/slides/123456.png

Step 6: Create View File 

Now go to resources/views/ folder and reate new create.blade.php file and add following below code. 

<html lang="en">
<head>
  <title>Laravel 8 Upload Multiple Images Tutorial - phpicoder.com</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>Sorry!</strong> There were more problems with your HTML input.<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 8 Upload Multiple Images Tutorial - phpicoder.com</h3>
 
<form method="post" action="" enctype="multipart/form-data">
    @csrf
    <div class="sliderList">
      <div class="input-group control-group" >
        <input type="file" name="imageName[]" class="myfrm form-control">
        <div class="input-group-btn"> 
          <button class="btn btn-success addMoreSlider" type="button">Add More</button>
        </div>
      </div>
    </div>
    <div class="clone d-none">
      <div class="control-group input-group phpicoder" style="margin-top:5px">
        <input type="file" name="imageName[]" class="myfrm form-control">
        <div class="input-group-btn"> 
          <button class="btn btn-danger removeSliderImage" 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() {
      $(".addMoreSlider").click(function(){ 
          var cloneHTML = $(".clone").html();
          $(".sliderList").after(cloneHTML);
      });
      $("body").on("click",".removeSliderImage",function(){ 
          $(this).parent().parent(".phpicoder").remove();
      });
    });
</script>
  
</body>
</html>

Step 7: Run Laravel App

Start the laravel application with following command:

php artisan serve

After run above command we have a http://127.0.0.1:8000/slider url

I hope it can help you for how to upload multiple images in laravel 8 tutorial...