Laravel 10/9 Multiple File Upload with Validation Tutorial

To upload multiple files in Laravel 10/9; Through this tutorial, i am going to show you how to upload multiple file in Laravel 10/9 with validation. And store multiple files into database and public storage directory (folder).

In this example tutorial, i will implement multiple file upload form and store multiple files into database and directory in Laravel 10/9 apps with validation.

Laravel 10/9 Multiple File Upload With Validation

Use the below given simple steps to uploading multiple file in Laravel 10/9 apps:

  • Step 1 – Install Laravel 10/9 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Create Model & Migration
  • Step 4 -Create Upload Routes
  • Step 5 – Creating Upload Controller
  • Step 6 – Create Multiple File Upload Form
  • Step 7 – Start Development Server
  • Step 8 – Run This App On Browser

Step 1 – Install Laravel 10/9 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaraMultipleFileUpload

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaraMultipleFileUpload

Then create model and migration file by using the following command:

php artisan make:model File -m

The above command will create two files into your laravel multiple file upload tutorial app, which is located inside the following locations:

  • /app/Models/File.php
  • /database/migrations/create_files_table.php

So, find create_files_table.php file inside /database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('store_path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Upload Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\MultipleFileUploadController;

Route::get('files-upload', [MultipleFileUploadController::class, 'index']);

Route::post('files-upload', [MultipleFileUploadController::class, 'store']);

Step 5 – Creating Upload Controller

In step 5, create multiple file upload controller by using the following command:

php artisan make:controller MultipleFileUploadController

The above command will create MultipleFileUploadController.php file, which is located inside /app/Http/Controllers/ directory.

The following laravel validation rules will validate file before upload/save into database:

        
        $validatedData = $request->validate([
	    'files' => 'required',
        'files.*' => 'mimes:csv,txt,xlx,xls,pdf'
        ]);

So open MultipleFileUploadController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\File;


class MultipleFileUploadController extends Controller
{
    public function index()
    {
        return view('files-upload');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
	    'files' => 'required',
        'files.*' => 'mimes:csv,txt,xlx,xls,pdf'
        ]);


        if($request->hasfile('files'))
         {
            foreach($request->file('files') as $key => $file)
            {
                $path = $file->store('public/files');
                $name = $file->getClientOriginalName();

                $insert[$key]['name'] = $name;
                $insert[$key]['store_path'] = $path;

            }
         }

        File::insert($insert);

        return redirect('files-upload')->with('status', 'Multiple File has been uploaded into db and storage directory');

    }
}

The following single line of code will upload files inside storage/app/public/files directory:

        $path = $request->file('file')->store('public/files');

Step 6 – Create Multiple File Upload Form

In step 6, create new blade view file that named files-upload.blade.php inside resources/views directory for multiple file upload form.

Then create multiple file upload form on this files-upload.blade.php file:

        <form name="files-upload" method="POST"  action="{{ url('files-upload') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="files[]" placeholder="Choose files" multiple >
                    </div>
                    @error('files')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
                  
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

The following code display error message in laravel file upload forms. So do not forget to add the following code along laravel forms fields:

          @error('files')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

Don’t worry i have already added the validation error message display code along with form fields.

So, you can add the following php and html form code into files-upload.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 10/9 Multiple File Upload With Validation</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-5">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 10/9 Multiple File Upload Tutorial</h2>
    </div>

    <div class="card-body">
        <form name="files-upload" method="POST"  action="{{ url('files-upload') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="files[]" placeholder="Choose files" multiple >
                    </div>
                    @error('files')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
                  
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div>  
</body>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your Laravel 10/9 multiple file upload application:

php artisan serve

Step 8 – Run This App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/files-upload

Note that, in this example, the file will be upload on the following path – storage/app/public/files.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *