How to change Laravel Validation message for max file size in MB instead of KB?

- 1 answer


Laravel comes with this validation message that shows file size in kilobytes:

file' => 'The :attribute may not be greater than :max kilobytes.',

I want to customize it in a way that it shows megabytes instead of kilobytes. So for the user it would look like:

"The document may not be greater than 10 megabytes."

How can I do that?




You can extend the validator to add your own rule and use the same logic without the conversion to kb. You can add a call to Validator::extend to your AppServiceProvider.

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AppServiceProvider extends ServiceProvider
     * Bootstrap any application services.
     * @return void
    public function boot()
        Validator::extend('max_mb', function($attribute, $value, $parameters, $validator) {
            $this->requireParameterCount(1, $parameters, 'max_mb');

            if ($value instanceof UploadedFile && ! $value->isValid()) {
                return false;

            // If call getSize()/1024/1024 on $value here it'll be numeric and not
            // get divided by 1024 once in the Validator::getSize() method.

            $megabytes = $value->getSize() / 1024 / 1024;

            return $this->getSize($attribute, $megabytes) <= $parameters[0];

Then to add the error message you can just add it to your validation lang file.

See the section on custom validation rules in the manual