Home » Php » php – How to Validate on Max File Size in Laravel?

php – How to Validate on Max File Size in Laravel?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to validate on a max file size of 500kb in Laravel:

$validator = Validator::make($request->all(), [
    'file' => 'size:500',
]);

But this says that the file should be exactly 500kb big. How can I edit this rule so that it returns an error when it’s bigger than 500kb?

Ive tried this:

'file' => 'size:>=500'
'file'  => 'size:max:500'

The documentation says nothing about this:

size:value

The field under validation must have a size matching the given value.
For string data, the value corresponds to the number of characters. For
numeric data, the value corresponds to a given integer value. For files,
size corresponds to the file size in kilobytes.

How to&Answers:

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

Answer:

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named ‘upload’ so I was getting “The upload failed to upload.”. This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can’t do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly ‘file too large’ message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}