Laravel 9 Multiple Files Upload Example

Published On: 14/06/2022 | Category: Laravel Laravel 9

Hi Dev,

If you need to see example of Laravel 9 Multiple Files Upload Example. This tutorial will give you simple example of Laravel 9 Multiple File Upload Step by Step Example. I explained simply step by step How to Upload Multiple Files in Laravel 9 with Validation. You just need to some step to done Laravel 9 Upload Multiple Files Tutorial with Example.

I’m going to show you about laravel 9 multiple file upload in mysql database example.

This article will give you simple example of Laravel 9 Upload Multiple Files in MySQL Database with Validation Example

Let's start following example:

Step 1: Install Laravel

First of all we are going from scratch new laravel application. if you have already created the project, then skip following step.

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

create migration table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:migration create_files_table
database/migrations/create_files_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('files', function (Blueprint $table) {
            $table->id();
            $table->string('file');
            $table->timestamps();
        });
    }

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

now, we need to run migration command to create database table:

php artisan migrate
Step 3 : Create New Model

Here, we already have table created, so we need create model run command to create model:

php artisan make:model File
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',
    ];
}
Step 4 : Create Routes routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('/Multiple-File',[MultipleFileUploadController::class, 'index']);
Route::post('Multiple-File-Upload',[MultipleFileUploadController::class, 'store'])->name('file.store');
Step 5 : Create New Controller

In this second step, we need to create a new MultipleFileUploadController; in this file, we will add two method index() and store() for render view and store image logic.

Let's create MultipleFileUploadController by following command:

php artisan make:controller MultipleFileUploadController
app/Http/Controllers/MultipleFileUploadController.php
<?php

namespace App\Http\Controllers;

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

class MultipleFileUploadController extends Controller
{
    /**
     * Write Your Code..
     *
     * @return string
    */
    public function index()
    {
        return view('index');
    }

    /**
     * Write Your Code..
     *
     * @return string
    */
    public function store(Request $request)
    {
        $request->validate([
            'files' => 'required',
            'files.*' => 'required|mimes:pdf,csv,txt,xlx,xls|max:2048',
        ]);

        if ($request->hasFile('files')){
            
            $files = $request->file('files');
            foreach($files as $file)
            {   
                $fileName = $file->getClientOriginalName();  
                $file->move(public_path('files'), $fileName);

                $files[]['name'] = $fileName;
                File::create([
                    'file' => $fileName
                  ]);
            }
        }

        return back()->with('success','You have successfully upload files.');
    }
}
Step 6: Create Blade File resources/views/index.blade.php
<!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>Laravel 9 Multiple Files Upload Example</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="text-center">Laravel 9 Multiple Files Upload Example - Tuts-Station.com</h5>
                    </div>
                    <div class="card-body">
                        @if ($message = Session::get('success'))
                            <div class="alert alert-success alert-dismissible fade show mb-2" role="alert">
                                {{ $message }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                        <form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mt-3">
                                <label>Select Files : <span class="text-danger">*</span></label>
                                <input type="file" name="files[]" class="form-control @error('files') is-invalid @enderror" multiple>
                                
                                @error('files')
                                <span class="text-danger">{{ $message }}</span>
                                @enderror
                                
                                @error('files.*')
                                <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="text-center mt-3">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                            </div>     
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve
Output :

I hope it can help you...