Laravel 5中的图像阵列验证 [英] Image array validation in Laravel 5

查看:68
本文介绍了Laravel 5中的图像阵列验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My application allows the user to upload multiple image files at the same time, however I can't figure out how to validate the array of images.

$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 { ...

如果我将验证规则更改为:

This validation will fail, as 'image' is an array, if I change the validation rule to:

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

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

The validation will pass, but the images inside of the array haven't been verified.

此答案使用每个关键字以验证规则作为前缀,但这在laravel 4.2和Laravel 5中似乎无效.

This answer uses the keyword each to prefix validation rules, however this is in laravel 4.2 and in Laravel 5 it doesn't seem to work.

我一直在尝试遍历数组并分别验证每张图像,但是是否有内置函数可以帮我做到这一点?

I've been trying to iterate through the array and validation on each image individually, but is there a built in function to do this for me?

推荐答案

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

I used a technique similar to what Jeemusu recommended and after the initial validation to make sure the array of images is present, iterated through the array with a second validator, making sure each item in the array is in fact an image. Here's the code:

$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);

    }
}

这篇关于Laravel 5中的图像阵列验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆