How to Validate File Upload in Laravel: Simple Guide
In Laravel, you validate file uploads using the
validate method on the request object with rules like file, mimes, and max. This ensures the uploaded file meets your requirements before processing it.Syntax
Use the validate method on the request object with an array of rules for the file input name. Common rules include:
required: file must be presentfile: input must be a filemimes:jpg,png,pdf: allowed file typesmax:2048: max file size in kilobytes
php
request()->validate([
'file_input_name' => 'required|file|mimes:jpg,png,pdf|max:2048',
]);Example
This example shows a controller method that validates an uploaded image file named photo. It requires the file, checks it is an image, limits types to jpeg and png, and restricts size to 1MB.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UploadController extends Controller { public function uploadPhoto(Request $request) { $validated = $request->validate([ 'photo' => 'required|file|image|mimes:jpeg,png|max:1024', ]); // If validation passes, store the file $path = $request->file('photo')->store('photos'); return response()->json(['message' => 'File uploaded successfully', 'path' => $path]); } }
Output
{"message":"File uploaded successfully","path":"photos/filename.jpg"}
Common Pitfalls
Common mistakes include:
- Forgetting the
filerule, which can cause validation to pass even if the input is not a file. - Not specifying allowed
mimesormimetypes, leading to unexpected file types being accepted. - Setting
maxsize too high or forgetting it, which can cause large files to upload and slow your app. - Not handling validation errors properly, which can confuse users.
php
<?php // Wrong way: missing 'file' rule $request->validate([ 'document' => 'required|mimes:pdf,docx|max:2048', ]); // Right way: include 'file' rule $request->validate([ 'document' => 'required|file|mimes:pdf,docx|max:2048', ]);
Quick Reference
| Rule | Description | Example |
|---|---|---|
| required | File must be uploaded | 'photo' => 'required|file' |
| file | Input must be a file | 'document' => 'file' |
| mimes | Allowed file extensions | 'image' => 'mimes:jpg,png,gif' |
| mimetypes | Allowed MIME types | 'upload' => 'mimetypes:image/jpeg,image/png' |
| max | Max file size in KB | 'file' => 'max:2048' |
| image | File must be an image | 'avatar' => 'image' |
Key Takeaways
Always use the 'file' rule to ensure the input is a file.
Use 'mimes' or 'mimetypes' to restrict allowed file types.
Set 'max' to limit file size and protect your app.
Handle validation errors to give clear feedback to users.
Laravel's validate method makes file validation simple and secure.