Laravel

Uploading Multiple Files with Validation in Laravel 10

Are you building a web application that requires users to upload multiple files? Laravel 10 makes the process seamless with its powerful features for file handling and validation. In this tutorial, we'll guide you through the steps to implement a multiple file upload functionality with validation in Laravel 10.

Step 1: Install Laravel 10

To get started, let's create a new Laravel 10 project. Open your terminal and run the following command:

composer create-project laravel/laravel laravel_10_multiple_file_upload_example

Step 2: Set Up the Database and Model

Create a migration to set up the database table for storing file information:

// Run in the terminal
php artisan make:migration create_files_table

In the generated migration file, define the schema for the "files" table. We'll include a "name" column to store the file names.

// database/migrations/xxxx_xx_xx_create_files_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
   public function up()
   {
       Schema::create('files', function (Blueprint $table) {
           $table->id();
           $table->string('name');
           $table->timestamps();
       });
   }
   public function down()
   {
       Schema::dropIfExists('files');
   }
}

Run the migration to create the table in the database:

php artisan migrate

Next, create a model for the "File" table:

// Run in the terminal
php artisan make:model File

Step 3: Implement FileController

Generate a controller to handle file uploads and validation:

// Run in the terminal
php artisan make:controller FileController

In the controller, define the methods to show the upload form and process the uploaded files. We'll implement validation for file types and maximum file size.

// app/Http/Controllers/FileController.php
use Illuminate\Http\Request;
use App\Models\File;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class FileController extends Controller
{
   public function index(): View
   {
       return view('index');
   }  
   public function store(Request $request): RedirectResponse
   {
       $request->validate([
           'files' => 'required',
           'files.*' => 'required|mimes:pdf,xlsx,csv|max:2048',
       ]);
       
       $files = [];
       if ($request->file('files')){
           foreach($request->file('files') as $key => $file)
           {
               $file_name = time().rand(1,99).'.'.$file->extension();  
               $file->move(public_path('uploads'), $file_name);
               $files[]['name'] = $file_name;
           }
       }
       foreach ($files as $key => $file) {
           File::create($file);
       }
      
       return back()->with('success','File uploaded successfully');
   }
}

Step 4: Create Routes and Views

Define the routes in the `routes/web.php` file to link the controller methods:

use App\Http\Controllers\FileController;
Route::controller(FileController::class)->group(function(){
   Route::get('index', 'index');
   Route::post('store', 'store')->name('file.store');
});

Create a Blade view named `index.blade.php` to display the file upload form:

<!DOCTYPE html>
<html>
<head>
   <title>Upload Multiple Files in Laravel 10</title>
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
   <div class="container">
       <div class="panel panel-primary">
           <div class="panel-heading">
               <h2>Upload Multiple Files in Laravel 10</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('file.store') }}" method="POST" enctype="multipart/form-data">
                   @csrf
                   <div class="mb-3">
                       <label class="form-label">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 5: Run Your Application

Now you're all set! Launch your Laravel 10 application with the following command:

php artisan serve

Access the application in your web browser and navigate to the `/index` route to see the multiple file upload form in action.

Conclusion

In this tutorial, we've learned how to build a multiple file upload functionality with validation using Laravel 10. This feature is valuable for applications that require users to upload various documents, images, or other file types. By following these steps, you can create a user-friendly file upload experience that enhances the functionality of your Laravel application.

Leave A Comment