Laravel 11 Max File upload Size Validation Tutorial

Using this Laravel 11 Max File upload Size Validation Tutorial we will show you how to handle to validate max file upload in laravel application using below the step by step guide.

Step 1: Create the File Upload Form

Begin by designing a file upload form in the resources/views directory to enable users to select and submit a file:

<form action="{{ route('file.upload') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="uploaded_file">
    <button type="submit">Upload</button>
</form>

Step 2: Set Up Routes

In your routes/web.php file, establish the necessary routes for handling the file upload and validation:

use App\Http\Controllers\FileController;

Route::post('/file/upload', [FileController::class, 'handleUpload'])->name('file.upload');

Step 3: Implement File Size Validation

In your controller, apply validation rules for the uploaded file by using the validate() method with constraints for minimum and maximum file sizes:

public function handleUpload(Request $request)
{
$request->validate([
'uploaded_file' => 'required|file|min:512|max:5120', // Minimum file size: 512 KB, Maximum file size: 5 MB
], [
'uploaded_file.min' => 'The file must be at least :min kilobytes.',
'uploaded_file.max' => 'The file may not exceed :max kilobytes.',
]);

// Logic for processing the uploaded file

return redirect()->back()->with('success', 'File successfully uploaded.');
}

Step 4: Display Error Messages

In your view file, ensure you display error messages for any validation issues encountered:

@if ($errors->has('uploaded_file'))
<div class="alert alert-danger">{{ $errors->first('uploaded_file') }}</div>
@endif

Step 5: Run and Test

Launch your development server by running the following command in your command line or terminal:

php artisan serve

Test the file upload functionality by accessing the form via your web browser and checking that the file size limits are enforced correctly.