0

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!

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply. This doesn't tackle the file rule though, I am still getting the same validation error. I think I will just switch it to mimetype and see where that takes me instead of using file.
check the updated answer. It seems to be working for me. What laravel version you're on ?
Thanks for update. I'm hoping to allow pdfs or images, which is why I was using the file rule and not the image rule. I'll give your solution a try with the mimetypes rule and see how I get on when I back to coding. Thanks again!
Serious facepalm moment. I was updating an old and huge form and overlooked there were no existing file inputs, turns out the reason it wasn't working was that I missed out enctype="multipart/form-data".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.