haakym
haakym

Reputation: 12358

Laravel multiple file upload, input cannot be empty when using file validation rule

Summary

I have some simple markup for a file input that allows multiple files to be selected. The validation should allow the form to be submitted with the file input left blank/empty. However, when submitting the form without selecting any file or files I receive the following error:

The supporting_files.0 must be a file.

HTML

<div class="mb-3">
    <label for="supporting_files">Supporting Files</label>
    <input type="file" class="form-control-file" id="file" name="supporting_files[]" multiple>
</div>

Validation code

'supporting_files.*' => 'file|max:2048',

I have also tried using the sometimes and nullable rule but get the same behaviour.

'supporting_files.*' => 'sometimes|file|max:2048',
'supporting_files.*' => 'sometimes|nullable|file|max:2048',

Using nullable did allow me to submit an empty field, but then I get the same validation error when attaching a file: The supporting_files.0 must be a file.

I thought the solution to this would be possible using basic validation rules and now I am wondering if I need to write some logic to handle this, i.e. simple if statement to check if there is file(s) present then apply the validation rules. Any guidance on how to use the rules correctly, if possible, would be appreciated, thanks!

Upvotes: 0

Views: 578

Answers (1)

Akhzar Javed
Akhzar Javed

Reputation: 628

Add this into your validation array


'supporting_files' => ['nullable', 'array'],
'supporting_files.*' => ['image', 'mimes:png']

Let your validation know, supporting_files is array and it could be nullable Just tested and it passes the validation without error but supporting_files index is not present in $request->all()

Upvotes: 1

Related Questions