Laravel - validate file size when PHP max upload size limit is exceeded
You don't seem interested in changing the PHP limits to allow larger files. It looks to me like you want your max upload to be 5MB, and return a proper response if it is over that.
You can handle the FileException
exception inside your exception handler at app/Exceptions/Handler.php
. Update the render
method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException
exception.
public function render($request, Exception $exception)
{
if ($exception instanceof \Symfony\Component\HttpFoundation\File\Exception\FileException) {
// create a validator and validate to throw a new ValidationException
return Validator::make($request->all(), [
'your_file_input' => 'required|file|size:5000',
])->validate();
}
return parent::render($request, $exception);
}
This is untested, but should give you the general idea.You can also do client side validation via javascript, so that a file that is too large is never actually sent to your server, but javascript can be disabled or removed by the client, so it would be good to have nice server side handling set up.
For the client side validation, if you attach an event handler to the "change" event for the file input, you can check the file size using this.files[0].size
, and perform any additional actions after that (disable form, remove uploaded file, etc.)
How to Validate on Max File Size in Laravel?
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB. Laravel 6 upload_max_filesize , i just want to upload 5mb file size
Your validation seems correct. You will also need to increase the maximum post file and also upload size of php.
Please updates this values on your php.ini file.
upload_max_filesize = 5M
post_max_size = 5M
Related Topics
How to Get the Root Url of the Site
PHP - Swiftmailer Using Starttls and Self Signed Certificates
Extend Request Class in Laravel 5
How to Get the Absolute Path to the Public_HTML Folder
PHP Resize Image on or Before Upload
How to Get an Array of Data from $_Post
Having Trouble Writing to a File with PHP on Ubuntu
In Magento 1.9.0.0 How to Enable Template Path Hint
Why Is Object Oriented PHP with MySQLi Better Than the Procedural Approach
PHP Class: Global Variable as Property in Class
How to Generate a Round Robin Tournament in PHP and MySQL
Converting JSON to CSV Format Using PHP
Get the Get Variables from a Url String
Facebook Graph API - Friends Using Application