laravellaravel-5.1laravel-validation

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


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?


Solution

  • You can create your own rule, and use the same logic as existing rule, but without the conversion to KB.

    To do that, add a call to Validator::extend method in your AppServiceProvider.php file, like:

    <?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 change the error message, you can just edit your validation lang file.

    See also the section on custom validation rules in the manual