Raj
Raj

Reputation: 2028

Validate max number of multiple files that can be attached in Laravel Validation

I have a form that allows multiple files to be attached.

I am validating the form for attachment field as:

$this->validate($request, [

            'attachments.*' => 'mimes:jpg,jpeg,bmp,png|max:5000',
        ]);

It works properly but I also want to only allow maximum of 3 files to be uploaded at a time.

How do I achieve this ?

Upvotes: 7

Views: 8190

Answers (3)

Marinario Agalliu
Marinario Agalliu

Reputation: 1189

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!

Upvotes: 2

freelancer
freelancer

Reputation: 1164

As attachments is an array, you can use max rule to validate it max elements as 3

 $messages = [
    "attachments.max" => "file can't be more than 3."
 ];

 $this->validate($request, [

        'attachments.*' => 'mimes:jpg,jpeg,bmp,png|max:5000',
        'attachments' => 'max:3',
    ],$messages);

Upvotes: 14

Lovepreet Singh
Lovepreet Singh

Reputation: 4850

There is option to add Custom Validation Rules in laravel.

Also you can try something like this:

$this->validate($request, [
    'attachments.*' => [
        'mimes:jpg,jpeg,bmp,png',
        function($attribute, $value, $fail) {
            if (count($value) > 3) {
                return $fail($attribute . ' should be less than or equal to 3.');
            }
        },
    ]
]);

There is another solution posted here: How to validation number of files

Upvotes: 3

Related Questions