Laravel表单数组验证不起作用

时间:2018-08-17 11:14:16

标签: php laravel

我在使用Laravel 5.1验证数组时遇到麻烦。

HTML代码:

{!! Form::label('information[1][color]', 'Color') !!}
{!! Form::select('information[1][color]', [null => 'Choose your color'] + $product->availableColors()->toArray() , null, ['id' => 'select-color0', 'data-id' => $product->id, 'class' => 'form-control', 'required' => 'required']) !!}

要测试数据是否正确传递:

dd($request->all):

"information" => array:1 [▼
    1 => array:1 [▼
      "color" => "2"
    ]
  ]

验证码:

public function store(Request $request)
    {
        $rules = [
            'information.*.color' => 'required'
        ];

        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails()){
            dd('Validation fails');
            return Redirect::to('index')->withErrors($validator);
        } else {
            ..........

我一直停留在dd('Validation fails')的页面上。有人可以向我解释我在这里缺少什么,为什么验证不起作用?我正在尝试遵循本教程:https://mattstauffer.com/blog/form-array-validation-in-laravel-5-2/

我也尝试过:

$validator = Validator::make($request->all(), [
    'information' => 'required',
    'information.*.color' => 'required'
]);

但是验证仍然失败

还尝试更改表单名称:

{!! Form::select('information[][color]', [null => 'Choose your color'] + $product->availableColors()->toArray() , null, ['id' => 'select-color0', 'data-id' => $product->id, 'class' => 'form-control', 'required' => 'required']) !!}

但仍然没有运气

2 个答案:

答案 0 :(得分:1)

解决方案:

$rules = [
        'id' => 'required',
        'name' => 'required|string',
        'information' => 'required|array'
    ];

    foreach ($request->information as $key => $variant) {
        foreach($variant as $color){
            $rules['information.'.$key.'.color'] = 'required';
        }
    }

    $validator = Validator::make($request->all(), $rules);

答案 1 :(得分:0)

从选择名称中删除1

googleapis-common-protos

或将规则更改为

{!! Form::select('information[][color]', array_merge([null => 'Choose your color'],$product->availableColors()->toArray()) , null, ['id' => 'select-color0', 'data-id' => $product->id, 'class' => 'form-control', 'required' => 'required']) !!}