Laravel 9 Multiple Files Upload with Database Example

Sovary August 23, 2022 492
5 minutes read

In this tutorial I will show you upload multiple file in Laravel 9 with example. We will develop an Laravel application from scratch with basic. We will implement and take a look at example of multiple file upload Laravel 9 with preview before upload. Following below steps for uploading multiple file in Laravel 9.

First, we will download Laravel 9 and create simple HTML form with file input so that we can browse select multiple file from computer. After click a button to submit form, the files will store on server and insert record data into database.

So, without further more, let's follow the below steps to upload multiple files in the Laravel 9 example.

Laravel 9 Multiple Files Upload Example

You can follow the steps below to upload multiple files in Laravel 9: 

  • Step 1 - Install Laravel 9
  • Step 2 - Create Migration & Model
  • Step 3 - Create Controller
  • Step 4 - Add Route
  • Step 5 - Create Blade File (View)
  • Step 6 - Run Laravel Server

Step 1 - Install Laravel 9

Laravel is PHP framework, so first to have Laravel application you have to install and download and setup database connection. Anyway I have wrote an article how to do install and configure database.

Step 2 - Create Migration & Model

Next, we will create a table to store file name, for file will upload somewhere directory in server, and database just store the filename. We are going to create a Model class, you may use the --migration or -m option to generate a migration file.

Run following command to create Model file and Migration file.

php artisan make:model FileX -m

Then open the migration file and modified some changed code below

Open file database -> migrations -> 2022_08_9_012603_create_tb_filex.php

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

After do some changed in file above, let's run the command below to migrate table in database.

php artisan migrate

Step 3 - Create Controller

Now, we are going to create controller file with two methods, we store and upload files then other one method is to display render HTML form.

Before we implement that, we are going to execute the command as below

php artisan make:controller FileController

then the controller file will generate

Open file app -> Http -> Controllers -> FileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\FileX;
  
class FileController extends Controller
{

    public function index()
    {
        return view('index');
    }
    
    /**
     * Upload files and store record database
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'files' => 'required',
            'files.*' => 'required|mimes:pdf,xlx,csv,docx|max:2048',
        ]);
      
        $files = [];
        $path = public_path('uploads');
        if ($request->file('files'))
        {
            if(!is_dir($path))
            {
                mkdir($path);
            }
            foreach($request->file('files') as $key => $file)
            {
                $fileName = time().rand(1,99).'.'.$file->extension();  
                $file->move($path, $fileName);
                $files[]['filename'] = $fileName;
            }
        }
  
        foreach ($files as $key => $file)
        {
            FileX::create($file);
        }
     
        return back()->with('success','File upload!');
   
    }
}

Step 4 - Add Route

Now we have to add route links where to map URL and Controller method to run.

Open file routes -> web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FileController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(FileController::class)->group(function()
{
    Route::get('/', 'index');
    Route::post('/upload', 'store')->name('upload');
});

Step 5 - Create Blade File (View)

Next, we will create a blade file to render HTML form and to upload files, so let's copy below code

Create file resources -> views -> index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Files Upload Laravel 9- CamboTutorial.com</title>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Laravel 9 Multiple Files Upload- CamboTutorial.com</h2>
      </div>
      <div class="panel-body">
        @if ($message = Session::get('success'))
            <div class="alert alert-success alert-block">
                <strong>{{ $message }}</strong>
            </div>
        @endif
        <form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="mb-3">
                <label class="form-label" for="inputFile">Select Files:</label>
                <input type="file" name="files[] multiple class="form-control @error('files') is-invalid @enderror">
                @error('files')
                    <span class="text-danger">{{ $message }}</span>
                @enderror
            </div>
            <div class="mb-3">
                <button type="submit" class="btn btn-success">Upload</button>
            </div>
        </form>
      </div>
    </div>
</div>
</body>
</html>

Step 6 - Run Laravel Server

Finally, we are done, it's time for run testing our application. Let's run following command to start Laravel server

php artisan serve

Open your browser with link localhost:8000/ and browser your file with hold shift key select files to upload multiple files at once

 

You might also like...

Laravel  PHP  Laravel 9 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him