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.
Apr 18, 2025
3
Level 1
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
Level 41
2 likes
Please or to participate in this conversation.