I have a multiple file input field:
<input type="file" id="documents" name="documents[]" multiple>
In my ProjectRequest class, I have the following rules applied:
$documents = count($this->input('documents'));
foreach(range(0, $documents) as $index) {
$rules['documents.' . $index] = 'mimes:doc,pdf,jpeg,bmp,png|max:20000';
}
But when I try to upload a png or pdf I get the following validation error:
The documents.0 must be a file of type: doc, pdf, jpeg, bmp, png.
As suggested in the answers, instead of looping through the array, I directly added the documents.*
rule in the $rules
array. However I still get the same error.
In ProjecRequest:
$rules = [
'documents.*' => 'mimes:doc,pdf,jpeg,bmp,png|max:20000',
];
return $rules;
In ProjectController@store:
public function store(ProjectRequest $request)
{
$project = Project::create([
/*key=>value removed to keep the question clean*/
]);
foreach ($request->documents as $document) {
$filename = $document->store('documents');
Document::create([
'project_id' => $project->id,
'filepath' => $filename
]);
}
return redirect()->back();
}
You don't need to loop
through the array, rather use *
.
$rules['documents.*'] = 'mimes:doc,pdf,jpeg,bmp,png|max:20000';
Read Laravel Official doc for better understanding.