Laravel 8 Multiple File Upload Tutorial

Multiple file upload in laravel 8. In this post, i would love to show you how to upload multiple file in laravel 8 with validation. And store multiple files into database and public storage directory (folder).

In this example post, i will implement multiple file upload form in laravel 8. And validate file mime type like pdf, txt, excel, xlsx, csv before upload into database and public storage directory.

In laravel 8, Multiple file uploading is a very easy task of uploading more than one file at the same time. Also validate and store it into database and directory.

Laravel 8 multiple file upload validation app will look like in below image:

Laravel 8 Multiple File Upload With Validation

Simple steps to uploading multiple file in laravel 8 app:

  • Step 1 – Install Laravel 8 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 8 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 8 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 8 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 8 multiple file upload tutorial app, which is located inside the following locations:

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

So, find create_files_table.php file inside LaravelFileUpload/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 LaraMultipleFileUpload/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 8 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 8 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 8 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.

Leave a Comment