Laravel 5中的图像阵列验证

蒂莫西·布克图

我的应用程序允许用户同时上传多个图像文件,但是我不知道如何验证图像数组。

$input = Request::all();

    $rules = array(
        ...
        'image' => 'required|image'
    );

    $validator = Validator::make($input, $rules);

    if ($validator->fails()) {

        $messages = $validator->messages();

        return Redirect::to('venue-add')
            ->withErrors($messages);

    } else { ...

'image'如果将验证规则更改为:此验证将失败,就像数组一样。

    $rules = array(
        ...
        'image' => 'required|array'
    );

验证将通过,但尚未验证数组内部的图像。

这个答案使用关键字each作为验证规则的前缀,但是这在laravel 4.2和Laravel 5中似乎不起作用。

我一直在尝试分别遍历每个图像的数组和验证,但是是否有内置函数可以帮我实现这一点?

蒂莫西·布克图

我使用了一种与Jeemusu建议的技术类似的技术,并在进行初始验证后确保存在图像阵列,并使用第二个验证器遍历该阵列,确保该阵列中的每个项目实际上都是一幅图像。这是代码:

$input = Request::all();

$rules = array(
    'name' => 'required',
    'location' => 'required',
    'capacity' => 'required',
    'description' => 'required',
    'image' => 'required|array'
);

$validator = Validator::make($input, $rules);

if ($validator->fails()) {

    $messages = $validator->messages();

    return Redirect::to('venue-add')
        ->withErrors($messages);

}

$imageRules = array(
    'image' => 'image|max:2000'
);

foreach($input['image'] as $image)
{
    $image = array('image' => $image);

    $imageValidator = Validator::make($image, $imageRules);

    if ($imageValidator->fails()) {

        $messages = $imageValidator->messages();

        return Redirect::to('venue-add')
            ->withErrors($messages);

    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章