Upload Multiple Images and Files with Validation in Laravel

Through this Laravel Upload Multiple Images example tutorial we will show you how to upload multiple files in Laravel app. Uploading multiple files with preview is a primary requirement in the admin panel. So we have added the best and easy example to upload multiple images and save them to the database with showing the validation error messages.

Here we will upload multiple files in Laravel and store them in the database as well as add in a storage directory.

How to Upload Multiple Images in Laravel

Follow the following steps to upload multiple files/images in laravel apps;

  • Step 1 – Download Laravel App
  • Step 2 – Connecting Database to App
  • Step 3 – Generate Model & Migration
  • Step 4 – Add Routes
  • Step 5 – Create Controller
  • Step 6 – Create Blade View
  • Step 7 – Run Development Server

Step 1: Download Laravel App

First, open your terminal and run the following command to download the fresh Laravel application.

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

Go inside the app:

cd laravel-multiple-images

Step 2: Connecting Database to App

Open the .env file and add your database credentials such as database name, username equally important password:

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

Step 3: Generate Model & Migration File

Next step, we need to execute the following command on the terminal to generate the model, and migration file using the following command:

php artisan make:model File -m

Place the below code in the app/Models/File.php file:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    protected $fillable = ['name', 'path'];
}

Now open the newly generated database/migrations/2020_04_29_161134_create_files_table.php file and put the below code on it;

<?php

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

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', 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('files');
    }
}

Next, open the command prompt and execute the following command to create the table in database:

php artisan migrate

Step 4: Add Routes

In this step, Navigate to the routes folder and open web.php. Then add the following routes into the web.php file:

<?php

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

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

Step 5: Create Controller

Now create the controller for crud operation. Here we are using File Controller you can use as per your requirements.

php artisan make:controller FileController

Open and update the below code in app\Http\Controllers\FileController.php;

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\File;

class FileController extends Controller
{
    public function index()
    {

      return view('files');
    }

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

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

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

                File::create([
                    'name' => $name,
                    'path' => '/storage/'.$path
                  ]);
            }
         }
         
        return back()->with('success', 'Files uploaded successfully');
    }
}

Step 6: Create Blade File

Now you need to create a blade file named as files.blade.php inside the resources/views directory. Now open resources\views\files.blade.php and put the below code on it;l

<!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 7 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 7 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('files.store') }}" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
          <input type="file" name="files[]" 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>

Step 7: Run Development Server

The last step, open the command prompt and run the following command to start development server:

php artisan serve

Then open your browser and hit the following URL on it:

http://127.0.0.1:8000/files

NOTE: Run the Laravel storage link command for uploading images in the public and storage directories.

php artisan storage:link

Finally, Laravel Upload Multiple Files Images Tutorial With Example is over now. I hope this will help you.

2 thoughts on “Upload Multiple Images and Files with Validation in Laravel”

Leave a Comment