Uploading Files and Validating Uploads
File uploads — profile pictures, documents, attachments — are a common requirement in real applications, and Laravel provides a clean, consistent way to accept and validate them before anything gets saved.
Accepting a File Upload
A file input in an HTML form must include the enctype="multipart/form-data" attribute, or the file simply won't be sent. On the Laravel side, the uploaded file is accessible through the request object as an instance of Laravel's file class, which wraps helpful metadata like original name and size.
Validating Uploaded Files
Just like any other form input, uploaded files should be validated before being trusted or stored. Laravel includes several rules specifically for files, covering type, size, and even image dimensions.
| Rule | What It Checks |
|---|---|
file | Confirms the input is a successfully uploaded file |
image | Restricts the upload to common image formats |
mimes:pdf,docx | Restricts uploads to specific file extensions |
max:2048 | Limits file size, specified in kilobytes |
dimensions:min_width=100 | Enforces minimum or maximum image dimensions |
Good Practices for Uploads
- Always validate file type and size before processing an upload
- Never trust the original filename as safe to use directly
- Generate a new, unique filename when storing an uploaded file
Once a file passes validation, it needs somewhere to actually live — which raises the question of where Laravel stores files, and the difference between its public and storage folders.
A Complete Upload Flow
Here is a minimal but realistic example: a user uploads a profile photo, and the app validates and stores it. Start with the form:
<form action="{{ route('avatar.update') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="avatar" accept="image/*">
@error('avatar') <p>{{ $message }}</p> @enderror
<button type="submit">Upload</button>
</form>
Then the controller method:
public function update(Request $request)
{
$request->validate([
'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
]);
$path = $request->file('avatar')->store('avatars', 'public');
$request->user()->update(['avatar_path' => $path]);
return back()->with('status', 'Photo updated');
}
What happens, step by step:
- The browser sends the file as multipart form data with the CSRF token.
- If validation fails, Laravel redirects back and the
@errorblock shows the message. store()creates a random, unique filename and saves it instorage/app/public/avatars.- Only the relative path is saved in the database, not the file itself.
Run php artisan storage:link once so files on the public disk can be reached through the public/storage link.
Richer Validation Options
The mimes rule checks the detected MIME type of the content, not just the extension the user typed, so a renamed executable will not pass as a PNG. Newer Laravel versions also offer a fluent rule object:
use Illuminate\Validation\Rules\File;
$request->validate([
'report' => ['required', File::types(['pdf', 'docx'])->max('5mb')],
'photos' => ['array', 'max:5'],
'photos.*' => ['image', 'max:2048'],
]);
The photos.* key applies the rule to each file in a multi-file input named photos[].
Storing Private Files Safely
Not every upload should be public. Invoices, ID documents and contracts belong on a private disk, served through a controller that checks permission first:
$path = $request->file('invoice')->store('invoices'); // default private disk
public function download(Invoice $invoice)
{
$this->authorize('view', $invoice);
return Storage::download($invoice->file_path);
}
This way, guessing a URL never exposes another user's document.
A few more defensive habits are worth adopting. Do not build a storage path from the original client filename, since it can contain odd characters or path segments; use store() or hashName() instead. If you must show the original name, save it in a separate column and escape it when displaying. For public images, consider re-encoding or resizing them with an image library, which also strips unexpected embedded data. Finally, never place uploads in a folder where the web server would execute PHP files.
Upload Problems and How to Prevent Them
| Problem | Fix |
|---|---|
$request->file() returns null | Add enctype="multipart/form-data" to the form |
| Large files fail before validation runs | Raise upload_max_filesize and post_max_size in PHP settings, and the web server's body size limit |
| Uploaded image shows a 404 | The storage link is missing or the wrong disk was used |
| Old files pile up | Delete the previous file with Storage::disk('public')->delete($old) when replacing it |
Checklist: multipart form, CSRF token, type and size rules, generated filenames, private disk for sensitive files, and authorization before downloads.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.