Table Of Contents
Laravel's Built-in Solution: The file()
Method
File uploads are tricky, but Laravel's $request->file()
method handles the heavy lifting. Here's how to grab that uploaded file safely:
// Basic file retrieval
public function upload(Request $request)
{
// Get the uploaded file
$file = $request->file('avatar');
// Check if file was uploaded successfully
if ($file && $file->isValid()) {
// File is ready to use
$filename = $file->store('avatars'); // Stores in storage/app/avatars
return response()->json(['path' => $filename]);
}
return response()->json(['error' => 'No file uploaded'], 400);
}
// With validation
public function uploadWithValidation(Request $request)
{
$request->validate([
'document' => 'required|file|mimes:pdf,doc,docx|max:2048' // 2MB max
]);
$file = $request->file('document');
// Store with custom name
$path = $file->storeAs('documents',
'user_' . auth()->id() . '_' . time() . '.' . $file->getClientOriginalExtension()
);
return response()->json(['success' => true, 'file_path' => $path]);
}
File Upload Error Handling
The file()
method returns null
if no file is uploaded, and the isValid()
method catches upload errors like UPLOAD_ERR_INI_SIZE
or UPLOAD_ERR_PARTIAL
. Always check both conditions to avoid "Call to a member function on null" errors.
Advanced file handling with multiple checks:
public function handleFileUpload(Request $request)
{
$file = $request->file('upload');
// Multiple validation layers
if (!$file) {
return response()->json(['error' => 'No file provided'], 422);
}
if (!$file->isValid()) {
return response()->json(['error' => 'File upload failed: ' . $file->getErrorMessage()], 422);
}
// Get file information
$originalName = $file->getClientOriginalName();
$mimeType = $file->getMimeType();
$size = $file->getSize(); // in bytes
$extension = $file->getClientOriginalExtension();
// Custom validation
if ($size > 5 * 1024 * 1024) { // 5MB
return response()->json(['error' => 'File too large'], 422);
}
// Store to specific disk
$path = $file->store('uploads', 's3'); // Store to S3
// Save file info to database
$upload = FileUpload::create([
'original_name' => $originalName,
'file_path' => $path,
'mime_type' => $mimeType,
'file_size' => $size,
'user_id' => auth()->id()
]);
return response()->json([
'message' => 'File uploaded successfully',
'file' => $upload
]);
}
// Alternative: hasFile() method for checking existence
if ($request->hasFile('image') && $request->file('image')->isValid()) {
// Process the file
}
Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Building Multi-tenant Applications with Laravel: A Comprehensive Guide | Level Up Your Laravel Validation: Advanced Tips & Tricks | Custom Laravel Validation Rules: Beyond the Basics
Share this article
Add Comment
No comments yet. Be the first to comment!