mattm591's avatar

[L5] Validating multiple file input

I have a multiple file upload which sends an array of image files to Laravel. The images array can be accessed fine, but the validation rules I specified are always returning false because the value is an array, not a file.

I'm using a Request with a rules function, defined as:

public function rules()
{
    $rules = [
        'name'          => 'required|max:500',
        'code'          => 'required|unique:products|max:500',
        'description'   => 'required',
        'image'         => 'image|max:4000',
    ];

    return $rules;
}

I considered extending the validate function in Illuminate\Validation\Validator, but didn't have much luck (not really sure how to define it, tried a few different ways but always either got errors or it just didn't have any effect).

Can anyone suggest a way I can handle validation of an array of files globally, without having to do more manual validation by iterating my files.

0 likes
9 replies
bestmomo's avatar
Level 52
public function rules()
{
    $rules = [
        'name'          => 'required|max:500',
        'code'          => 'required|unique:products|max:500',
        'description'   => 'required'
 ];

$nbr = count($this->input('image')) - 1;
foreach(range(0, $nbr) as $index) {
    $rules['image.' . $index] = 'image|max:4000';
}

    return $rules;
}
6 likes
simplenotezy's avatar

@ctf0 it does not work if you wish to validate the array value. I.e. you cannot do:

image.* => image

You have to do something like

image.*.file => image
3 likes
ctf0's avatar

@canfiax really !!! why in the gods name they don't include this in the docs ?!! , anyway i will test it today and get back to u, thanx for ur help :)

ctf0's avatar

@canfiax that didnt work, its as in the docs, simply image.* will validate each item in the array but the error will always come back as required

zizi_ove's avatar

this code solved my problem for validating array of images. (name of image field in form is : file)

    $request->validate([
        'product_code'  =>  'required|string',
        'product_name'  =>  'required|string',
        'product_price' =>  'required|string',

        'file'          =>  'nullable',                           //name of image field in form
        'file.*'          =>  'max:2048|image'        //name of image field in form
    ]);

Please or to participate in this conversation.