On this page
The Complete Guide to Laravel File Uploads: From Basic to Advanced
Handling file uploads is a common requirement in web applications, and Laravel makes this process secure and straightforward. In this guide, we'll cover everything from basic file uploads to advanced features and security best practices.
Basic File Uploads
Let's start with a simple file upload form:
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="document">
<button type="submit">Upload</button>
</form>
And the corresponding controller method:
public function upload(Request $request)
{
$path = $request->file('document')->store('documents');
return $path; // Returns the file path
}
File Validation
Laravel provides robust validation for file uploads:
$validated = $request->validate([
'document' => 'required|file|mimes:jpg,pdf,png|max:2048',
]);
Common validation rules:
required: Field must be presentfile: Must be an uploaded filemimes:jpg,pdf,png: Allowed file typesmax:2048: Maximum size in KB (2MB)dimensions:min_width=100,min_height=200: For image dimensions
Storing Files
Laravel's filesystem provides multiple storage options:
// Store in default disk
$path = $request->file('avatar')->store('avatars');
// Store with custom filename
$path = $request->file('avatar')->storeAs(
'avatars',
$request->user()->id
);
// Store publicly
$path = $request->file('avatar')->storePublicly('avatars', 's3');
Storage Disks Comparison
| Disk | Description | Use Case |
|---|---|---|
| local | Local storage | Development, small apps |
| public | Publicly accessible | User uploads, assets |
| s3 | Amazon S3 | Production, scalable |
| ftp | FTP/SFTP server | Legacy systems |
Advanced Features
Image Manipulation
Using Intervention Image package:
use Intervention\Image\Facades\Image;
$image = $request->file('avatar');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)
->resize(300, 200)
->save(public_path('images/' . $filename));
File Streaming
For large files:
return Storage::disk('s3')->response('file.jpg');
Temporary URLs
Generate temporary URLs for private files:
$url = Storage::temporaryUrl(
'file.jpg',
now()->addMinutes(5)
);
Security Best Practices
- Always validate file types: Don't rely on client-side validation
- Use proper permissions: Set correct file permissions
- Scan for viruses: Consider using a virus scanner
- Store files outside webroot: When possible
- Use original file names with caution: Sanitize or generate new names
Handling Multiple Files
foreach ($request->file('photos') as $photo) {
$path = $photo->store('photos');
// ...
}
Testing File Uploads
public function test_avatar_upload()
{
Storage::fake('avatars');
$response = $this->post('/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
Storage::disk('avatars')->assertExists('avatar.jpg');
}
Performance Optimization
- Use queued jobs for processing large files
- Implement chunked file uploads for large files
- Use CDN for static assets
- Compress images on upload
Common Pitfalls
- Forgetting
enctype="multipart/form-data" - Not handling file upload errors
- Storing files with original names (security risk)
- Not setting proper file permissions
- Not cleaning up temporary files
Frequently Asked Questions
Q: What's the maximum file size I can upload? A: By default, PHP limits uploads to 2MB. You can increase this in your php.ini file.
Q: How can I rename files before storing?
A: Use the storeAs method with a generated filename:
$filename = time() . '.' . $request->file('avatar')->extension();
$path = $request->file('avatar')->storeAs('avatars', $filename);
Q: How do I delete an uploaded file? A: Use the Storage facade:
Storage::delete($filePath);
Q: Can I validate image dimensions? A: Yes, use the dimensions rule:
'document' => 'dimensions:min_width=100,min_height=200'
Q: How do I handle file downloads? A: Use the download response:
return Storage::download('file.jpg');
Conclusion
File handling in Laravel is powerful yet straightforward. By following these best practices, you can ensure secure and efficient file uploads in your applications. For more Laravel tips and tutorials, visit mahbuburriad.com.
Remember to always validate and sanitize user uploads, use appropriate storage drivers for your needs, and implement proper error handling for the best user experience.