When I started working with file uploads in Laravel 12, I quickly realized how important good validation is. It’s not just about making sure the file uploads — it’s about protecting the app and the users.
In this guide, I’ll show you how to validate file uploads properly in Laravel 12, using simple and clean code.
php artisan make:controller FileUploadController
<form action="{{ route('file.upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
use App\Http\Controllers\FileUploadController;
Route::get('/upload', function () {
return view('upload');
});
Route::post('/upload', [FileUploadController::class, 'store'])->name('file.upload');
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:jpg,jpeg,png,pdf|max:2048',
]);
$file = $request->file('file');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move(public_path('uploads'), $fileName);
return back()->with('success', 'File uploaded successfully!');
}
}
$request->validate([
'file' => 'required|mimes:jpg,jpeg,png,pdf|max:2048',
], [
'file.required' => 'Please choose a file to upload.',
'file.mimes' => 'Only jpg, jpeg, png, and pdf files are allowed.',
'file.max' => 'File size must not exceed 2MB.',
]);
$request->validate([
'files.*' => 'required|mimes:jpg,jpeg,png,pdf|max:2048',
]);
Handle multiple uploads easily:
foreach ($request->file('files') as $file) {
$fileName = time().'_'.$file->getClientOriginalName();
$file->move(public_path('uploads'), $fileName);
}
File upload validation in Laravel 12 isn't just about checking file types — it's about keeping your application strong and user-friendly. By following clean, simple validation rules, you make sure your app runs safely without annoying users.
Use files.*
in your validation rule and loop through uploaded files.
Use the max:
rule, like max:2048
for a 2MB file size limit.
Yes, use mimes:jpg,jpeg,png
or the image
rule to allow only image uploads.
Pass an array of custom messages as the second argument in $request->validate()
.
It's common, but for sensitive files, you should use Laravel's storage system with private visibility settings.
For more detailed information, refer to the official Laravel documentation on validation.
You might also like: