The validate() method allows users to validate the maximum and minimum size of a file uploaded in Laravel.
Let’s start to validate min and max file size:
Step 1: Create File Upload Form
Create form in resources/views
folder that allow users to choose file from form:
<form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload File</button>
</form>
Step 2: Define Routes
In routes/web.php
file, define routes for file upload and validation:
use App\Http\Controllers\YourController;
Route::post('/upload', [YourController::class, 'upload'])->name('upload');
Step 3: Validate Max & Min File Size
In your Laravel controller, define validation rules for the uploaded file using the validate()
method with min and max to handle file validation:
public function upload(Request $request)
{
$request->validate([
'file' => 'required|file|min:1024|max:10240', // Minimum file size: 1 KB, Maximum file size: 10 MB
], [
'file.min' => 'The file must be at least :min kilobytes.',
'file.max' => 'The file may not be greater than :max kilobytes.',
]);
// File upload logic here
return redirect()->back()->with('success', 'File uploaded successfully.');
}
Step 4: Error Handling
In your view file, include error messages for file validation errors if any:
@if ($errors->has('file'))
<div class="alert alert-danger">{{ $errors->first('file') }}</div>
@endif
Step 5: Test Application
Start cmd or terminal and run the following command to start application server:
php artisan serve
Test your file upload form with the maximum size specified using routes on the browser.