Quantcast
Channel: User zarpio - Stack Overflow
Viewing all articles
Browse latest Browse all 39

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

$
0
0

In Laravel 8

To generate a new validation rule.

php artisan make:rule MaxSizeRule

Edit your rule as follows.

<?phpnamespace App\Rules;use Illuminate\Contracts\Validation\Rule;class MaxSizeRule implements Rule{    private $maxSizeMb;    /**     * Create a new rule instance.     *     * @return void     */    public function __construct($maxSizeMb = 8)    {        $this->maxSizeMb = $maxSizeMb;    }    /**     * Determine if the validation rule passes.     *     * @param  string  $attribute     * @param  mixed  $value     * @return bool     */    public function passes($attribute, $value)    {        $megabytes = $value->getSize() / 1024 / 1024;        return $megabytes < $this->maxSizeMb;    }    /**     * Get the validation error message.     *     * @return string     */    public function message()    {        return 'The :attribute may not be greater than ' . $this->maxSizeMb . ' MB.';    }}

Use in your validation request as follow

return [    ...'banner_image' => ['required', 'file', 'mimes:jpeg,png,jpg,svg', new MaxSizeRule(10)],    ...];

Viewing all articles
Browse latest Browse all 39

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>