Laravel多文件验证失败

时间:2018-01-16 08:48:47

标签: php forms laravel validation laravel-validation

我有一个多文件输入字段: $documents = count($this->input('documents')); foreach(range(0, $documents) as $index) { $rules['documents.' . $index] = 'mimes:doc,pdf,jpeg,bmp,png|max:20000'; }

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

documents.*

但是当我尝试上传png或pdf时,我收到以下验证错误:

  

documents.0必须是以下类型的文件:doc,pdf,jpeg,bmp,png。

更新

正如答案中所建议的那样,我直接在$rules数组中添加$rules = [ 'documents.*' => 'mimes:doc,pdf,jpeg,bmp,png|max:20000', ]; return $rules; 规则,而不是循环遍历数组。但是我仍然得到同样的错误。

在ProjecRequest中:

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

在ProjectController @ store中:

Java Play

2 个答案:

答案 0 :(得分:2)

您不需要loop通过数组,而是使用*

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

阅读Laravel Official doc以便更好地理解。

答案 1 :(得分:1)

您可以使用以下命令验证数组:

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

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