It seems like you're having trouble with Laravel's validation not restricting the file size as expected. Your validation rule looks correct for a maximum file size of 10MB, as max:10000 specifies the size in kilobytes.
However, if users are still able to upload files larger than 10MB, there are a couple of things you should check:
-
PHP Configuration: PHP has its own file upload size restrictions, configured in
php.ini. Theupload_max_filesizeandpost_max_sizedirectives should be set to a value that accommodates your maximum file size requirement. For a 10MB file, you might want to set these values to12Mor more to provide a little overhead. -
Client-Side Validation: While server-side validation is crucial, you can also provide client-side validation to immediately inform users if the file is too large before attempting to upload it. However, remember that client-side validation can be bypassed, so server-side validation should always be in place as a fallback.
-
Error Handling: Ensure that your code is properly handling validation errors. If the validation fails, Laravel will throw a
ValidationException, which you should catch and handle appropriately, typically by redirecting back to the form with error messages.
Here's an example of how you might handle the validation in your controller:
public function store(Request $request)
{
try {
$validatedData = $request->validate([
'pdf' => 'required|file|mimes:pdf|max:10000', // 10MB
]);
// The file is valid, you can proceed with storing the file
// ...
} catch (\Illuminate\Validation\ValidationException $e) {
// Handle the validation exception
return redirect()->back()
->withErrors($e->validator)
->withInput();
}
}
And for the client-side validation, you can add a simple JavaScript check:
<form action="{{ route('pdf.store') }}" method="POST" enctype="multipart/form-data" class="mt-8 space-y-6" id="uploadForm">
@csrf
<input type="file" name="pdf" id="pdfFile" onchange="validateSize(this)">
<button type="submit">Upload</button>
</form>
<script>
function validateSize(fileInput) {
const fileSize = fileInput.files[0].size / 1024 / 1024; // in MB
if (fileSize > 10) {
alert('File size exceeds 10 MB');
// Clear the file input
fileInput.value = '';
}
}
</script>
Remember to check your php.ini settings and adjust them if necessary. If you're using shared hosting or do not have access to php.ini, you may need to contact your hosting provider to change these settings for you.