0

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.

Update:

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

2 Answers 2

2

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.

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

9 Comments

I removed the loop. Added this new rule to $rules[] array and I am still getting the same error
check your file type that you uploaded and show us your full validation code
checked, it was png.
Updated question.
did you enable multipart formdata in your form in blade file?? Could you show us full form from blade/view file.
|
1

You can validate arrays with:

'documents.*' => 'mimes:doc,pdf,jpeg,bmp,png|max:20000'

https://laravel.com/docs/5.5/validation#validating-arrays

6 Comments

I removed the loop. Added this new rule to $rules[] array and I am still getting the same error
@Eisenheim that is not error. It's the validation works as expected. It means the file you're trying to upload has the wrong mime type.
Tested with multiple files. All of them can't have wrong mime type @alexey-mezenin
@Eisenheim well, looks like they have.
Are you sure using only documents.* is the appropriate rule? Because nowhere in the documentation I see that rule. The documentation suggests this format documents.*.filename
|

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.