Laravel 5 验证图像上载

Laravel 5 验证图像上载,laravel-5,Laravel 5,哟!!我正在制作一个表格,在上面我附加了一些图片 表格: 验证: $this->validate($response, array( 'attachments' => 'required | mimes:jpeg,jpg,png', )); 我也尝试将“图像”作为验证规则,但每当我发布带有jpg图像的表单时,都会返回错误: 附件必须是以下类型的文件:jpeg、jpg、png 使用Laravel 5.3由于您定义了附件[]的输入名称,附件将是一个包含文件的数组。如果您只需要上

哟!!我正在制作一个表格,在上面我附加了一些图片

表格:

验证:

$this->validate($response, array(
    'attachments' => 'required | mimes:jpeg,jpg,png',
));
我也尝试将“图像”作为验证规则,但每当我发布带有jpg图像的表单时,都会返回错误:

附件必须是以下类型的文件:jpeg、jpg、png


使用Laravel 5.3

由于您定义了附件[]的输入名称,附件将是一个包含文件的数组。如果您只需要上载一个文件,您可能希望将输入名称重命名为
附件
,而不使用
[]
(或者
附件
,在这种情况下更有意义)。如果您需要能够上传多个,您可以在
请求
扩展类中构建一个迭代器,该类返回一组规则,涵盖
附件[]中的每个条目

protected function attachments()
{
    $rules          = [];
    $postedValues   = $this->request->get('attachments');

    if(null == $postedValues) {
        return $rules;
    }

    // Let's create some rules!
    foreach($postedValues as $index => $value) {
        $rules["attachments.$index"] = 'required|mimes:jpeg,jpg,png';
    }
    /* Let's imagine we've uploaded 2 images. $rules would look like this:
        [
            'attachments.0' => 'required|mimes:jpeg,jpg,png',
            'attachments.1' => 'required|mimes:jpeg,jpg,png'
        ];
    */

    return $rules;
}
然后,您可以在
rules()
内调用该函数,将从
附件返回的数组与您可能要为该请求指定的任何其他规则合并:

public function rules()
{
    return array_merge($this->attachments(), [
       // Create any additional rules for your request here... 
    ]);
}
如果您的表单还没有专用的
请求
-扩展类,则可以使用artisan cli输入:
php artisan make:Request MyRequestName
。将在
app\Http\Requests
中创建一个新的请求类。这就是您将上面的代码放入其中的文件。接下来,您可以在控制器端点的函数签名中仅使用该类:

public function myControllerEndpoint(MyRequestName $request)
{
    // Do your logic... (if your code gets here, all rules inside MyRequestName are met, yay!)
}
public function myControllerEndpoint(MyRequestName $request)
{
    // Do your logic... (if your code gets here, all rules inside MyRequestName are met, yay!)
}