Laravel 8 Upload Multiple Images Example Tutorial

In this article we are going to share Laravel 8 Upload Multiple Images Example Tutorial step by step. Upload multiple files in any project is one of the most commonly used features in web-projects. To storing and upload multiple files in laravel app we use store the data in database and upload in public storage directory.

Multiple image upload allows the user to select multiple files at once and upload all files to the server in a single click. So, we have added a best step by step example to multiple image upload tutorial in laravel app.

Step 1: Install Laravel App

First at all you need to install a new laravel application using the following command;

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

Go inside the app;

cd multiple-images

Step 2: Setup env file

Next, open the .env file and set you database credentials such as database name, username and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=multiple_images
DB_USERNAME=root
DB_PASSWORD=

Step 3: Generate Model & Migration

Next, generate a model and migration file using the following command.

php artisan make:model Image -m

Next, open the app\Models\Image.php file and add the fillable properties in you model same as below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $fillable = [
      'name', 'path'
    ];
}

database\migrations\2020_09_13_082159_create_images_table.php

In Your migration file add two columns one for image name another is for path.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

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

Now run the below command and generate table in your database.

php artisan migrate

Step 4: Create Routes

Next, open the routes\web.php file and add routes to handle the multiple image implement in laravel.

<?php

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


Route::get('images', [ ImageController::class, 'index' ]);
Route::post('images', [ ImageController::class, 'store' ])->name('images.store');

Step 5: Create Controller

Next, create a controller using the below command.

php artisan make:controller ImageController

After successfully create controller open and put the below code on it, Here we have added two methods on it one index for showing for form and store for saving data in database and uploading in public and storage directory.

<?php

namespace App\Http\Controllers;

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

class ImageController extends Controller
{
    public function index()
    {

      return view('images');
    }

    public function store(Request $request)
    {
        $request->validate([
          'images' => 'required',
        ]);

        if ($request->hasfile('images')) {
            $images = $request->file('images');

            foreach($images as $image) {
                $name = $image->getClientOriginalName();
                $path = $image->storeAs('uploads', $name, 'public');

                Image::create([
                    'name' => $name,
                    'path' => '/storage/'.$path
                  ]);
            }
         }

        return back()->with('success', 'Images uploaded successfully');
    }
}

Step 6: Create Blade File

Next, create a images.blade.php file inside the resources/views directory. Now open the newly created resources\views\images.blade.php file and update the below code on it;

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Upload Multiple Files in Laravel 8 with Coding Driver</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />


<style>
.invalid-feedback {
  display: block;
}
</style>
</head>
<body>

<div class="container mt-4">
  <h2>Upload Multiple Files in Laravel 8 with- <a href="https://codingdriver.com/">codingdriver.com</a></h2>
    @if(session()->has('success'))
        <div class="alert alert-success">
            {{ session()->get('success') }}
        </div>
    @endif

    <form method="post" action="{{ route('images.store') }}" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
          <input type="file" name="images[]" multiple class="form-control" accept="image/*">
          @if ($errors->has('files'))
            @foreach ($errors->get('files') as $error)
            <span class="invalid-feedback" role="alert">
                <strong>{{ $error }}</strong>
            </span>
            @endforeach
          @endif
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
</div>
</body>
</html>

NOTE: Run the laravel storage link command for uploading images in public and storage directory.

php artisan storage:link

I hope Upload Multiple Images in Laravel 8 Tutorial with Example work for you. If you have any question please comment below.

9 thoughts on “Laravel 8 Upload Multiple Images Example Tutorial”

Leave a Comment