Validating a file uploader involves ensuring that the uploaded file meets certain criteria, such as file type, file size, and other requirements. In Laravel, you can use validation rules to perform file validation. Here's how you can validate a file uploader in Laravel:
In your FileUploadController
, update the uploadFile
method to include file validation rules:
public function uploadFile(Request $request)
{
$request->validate([
'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:10240', // Max size in kilobytes (10MB)
]);
if ($request->file('file')->isValid()) {
$file = $request->file('file');
$filename = time() . '_' . $file->getClientOriginalName();
$file->storeAs('uploads', $filename); // Store file in storage/app/uploads directory
return redirect('/upload')->with('success', 'File uploaded successfully!');
}
return redirect('/upload')->with('error', 'File upload failed. Please try again.');
}
Explanation:
'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:10240'
: This validation rule ensures that the file
field is required, is a file, has one of the specified MIME types (e.g., jpg, jpeg, png, pdf), and has a maximum size of 10MB (10240 kilobytes).Update your Blade view (upload.blade.php
) to display validation errors:
<!DOCTYPE html>
<html>
<head>
<title>File Uploader</title>
</head>
<body>
<h2>Upload File</h2>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
@if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<form action="{{ route('upload.file') }}" method="post" enctype="multipart/form-data">
@csrf
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
Explanation:
$errors->any()
) and displays them in an alert box.You can now test the file uploader by visiting the /upload
route in your browser and attempting to upload files that do not meet the validation criteria. Users will receive appropriate error messages if the file does not meet the specified requirements.
That's it! You've successfully validated a file uploader in Laravel. You can customize the validation rules and error messages to suit your application's requirements.