I think that the best way is to create a new validation rule.
As per Laravel 8
I managed this way:
1- Created a new rule executing this command:
php artisan make:rule UploadCount
2- Go find new rule UploadCount.php
under app/Rules
and paste this:
public function passes($attribute, $value)
{
return (count($value) <= 5) ? true : false;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
if ( \Config::get('app.locale') == 'en') {
return 'You cannot upload more than 5 images';
} else {
return 'Non puoi caricare piu di 5 immagini';
}
}
If you can see in my case the limit is 5 files but you can change it.
P.S. I did not removed if statement
from message()
method because someone may need it to have different messages in case of localization otherwise you can use lang
folder with automatic messages. In case your project is not multilang you can just:
return 'You cannot upload more than 5 images';
3- Now on your form request you should:
Import UploadCount
: use App\Rules\UploadCount;
.
and:
public function rules()
{
return [
'images' => 'required|mimes:jpeg,jpg,png|max:32768',
'images' => [new UploadCount()],
];
}
Happy coding!