Laravel 多文件验证失败

Laravel multi file validation fails

我有一个多文件输入字段: <input type="file" id="documents" name="documents[]" multiple>

在我的 ProjectRequest class 中,我应用了以下规则:

$documents = count($this->input('documents'));
foreach(range(0, $documents) as $index) {
    $rules['documents.' . $index] = 'mimes:doc,pdf,jpeg,bmp,png|max:20000';
}

但是当我尝试上传 png 或 pdf 文件时,出现以下验证错误:

The documents.0 must be a file of type: doc, pdf, jpeg, bmp, png.

更新:

正如答案中所建议的,我没有循环遍历数组,而是直接在 $rules 数组中添加了 documents.* 规则。但是我仍然得到同样的错误。

在项目请求中:


$rules = [
  'documents.*' => 'mimes:doc,pdf,jpeg,bmp,png|max:20000',
];
return $rules;

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

您不需要 loop 遍历数组,而是使用 *

$rules['documents.*'] = 'mimes:doc,pdf,jpeg,bmp,png|max:20000';

阅读 Laravel 官方 doc 以获得更好的理解。

您可以使用以下方法验证数组:

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

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