Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Carl-Tabuso's avatar

prepareForValidation(): coercing to array

I handle single or multiple file uploads in my api. In my request class, i want to coerce an instance of \Illuminate\Http\UploadedFile to an array if the client request sends only a single file. The issue is the validation can't catch it if it's not an array.

    public function rules(): array
    {
        return [
            'employee_id' => ['required', 'exists:employees,id'],
            'attachments.*' =>['required', 'file', 'mimes:pdf', 'max:10240'],
        ];
    }

So i was trying to do is smth like this:

    protected function prepareForValidation(): void
    {
        if (! is_array($this->file('attachments'))) {
            $this->merge(['attachments' => $this->array('attachments')]);
        }
    }

Played around it many times and it still won't work. I want to force a file into an array so that i don't have to check it again in my controller once i retrieved the validated data $request->validated().

For now, i have to settle to this:

    public function rules(): array
    {
        $attachmentValidations = ['required', 'file', 'mimes:pdf', 'max:10240'];

        $attachmentRules = is_array($this->file('attachments'))
            ? ['attachments.*' => $attachmentValidations]
            : ['attachments' => $attachmentValidations];

        return array_merge($attachmentRules, [
            'employee_id' => ['required', 'exists:employees,id'],
        ]);
    }

Help plsssssssss

0 likes
3 replies
kevinbui's avatar
Level 41

What about just keep it simple, make the attachments field always an array? If there is only one file then it will be an array of a single item.

2 likes
Carl-Tabuso's avatar

@kevinbui yeah, that's what i did

public function rules(): array
{
    return [
        'employee_id'   => ['required', 'exists:employees,id'],
        'attachments'   => ['required', 'array', 'max:15'],
        'attachments.*' => ['required', 'file', 'mimes:pdf', 'max:5000'],
    ];
}

Please or to participate in this conversation.