Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 File Upload Validation Example

Last Updated on April 8, 2024 by

To validate the file before storing it in Laravel 11; Create a file upload form and then create methods to validate the file before storing it in Laravel 11 applications using built-in validation rules in the controller method to validate the file.

Let’s see a step by step example of how to validate a file before uploading it to a laravel 11 application:

Step 1. Create File Upload Form

Create a form with the help of which the file will be uploaded, you can do this by creating a Blade View file inside the Resources/Views folder; As like the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center mt-5">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">File Upload</h5>
                    </div>
                    <div class="card-body">
                        <form action="{{ url('upload-validate') }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-3">
                                <label for="file" class="form-label">Choose File</label>
                                <input class="form-control" type="file" id="file" name="file">
                            </div>
                            <button type="submit" class="btn btn-primary">Upload</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS (optional) -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 2. Create Controller and Methods

Now create a controller file with the help of which file uploading and validation will be handled, for this you can use the following command:

Now in the controller (app/Http/Controllers/FileUploadController.php) file that has been created, create two methods in it, which will help to display the file upload form and send the file to the server for validation; Like the following:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function form()
    {
        return view('file-upload');
    }

    public function uploadValidate(Request $request)
    {
       $file = $request->file('file');
    
        // Handle file upload logic here
        
        return back()->with('success', 'File uploaded successfully!');
    }

}

Step 3. Use Validation in Method

The file are of different types like excel, csv, txt, zip, jpg etc and their sizes also vary, so you can validate files before uploading them to the server using Laravel’s built-in validation; Like the following:

        $request->validate([
            'file' => 'required|file|mimes:xlsx,csv,txt|max:2048', // Adjust file types and size as per your requirement
        ]);
    
        $file = $request->file('file');
    
        // Handle file upload logic here
        
        return back()->with('success', 'File uploaded successfully!');

Laravel has some more validation rules to validate the file, which are given in the table below, you can use these rules individually or add them to your validation logic as required. Yes, will make your file validation easier:

Validation RuleDescription
requiredThe file field is required and must be present.
fileThe field under validation must be a successfully uploaded file.
mimes:foo,bar,…The file under validation must have a MIME type corresponding to one of the listed extensions.
mimetypes:text/plain, application/pdfSimilar to the mimes rule but works with MIME types rather than file extensions.
max:valueThe file under validation must not exceed a maximum file size, specified in kilobytes.
dimensions:min_width,min_height,max_width,max_heightThe file under validation must be an image meeting the specified minimum and maximum dimensions.
imageThe file under validation must be an image (jpeg, png, bmp, gif, or svg).
videosThe file under validation must be a video file (mp4, mov, avi, wmv, etc.).
audioThe file under validation must be an audio file (mp3, wav, ogg, etc.).
between:min,maxThe file under validation must have a size between the given min and max values (in kilobytes).
dimensions_ratio:width,heightThe file under validation must have a width-to-height ratio equal to the specified aspect ratio.
dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000An alternative syntax for specifying minimum and maximum dimensions.

Or if you know about Laravel’s 11 built-in validation rules you can checkout this: https://laravel.com/docs/11.x/validation.

Step 4. Add File Upload Routes

To handle file upload requests, you need to add routes in routes/web.php file; Like the following:

// routes/web.php
use App\Http\Controllers\FileUploadController;

Route::get('file-upload-form', [FileUploadController::class, 'Form']);
Route::post('upload-validate', [FileUploadController::class, 'uploadValidate']);

Step 5. Display Validation Message

To display validation error and success message on the form you have to use the code given below in file-upload.blade.php file:

    @if ($errors->any())
        <div>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @if(session('success'))
        <div>
            {{ session('success') }}
        </div>
    @endif

Step 6. Test

Run this application for testing using the following command:

php artisan serve

Now open browser with url http://127.0.0.1:8000/file-upload-form.

Conclusion

That is all; You saw in this simple example how to verify a file before uploading or storing it in a Laravel 11 application.

Leave a Comment