在laravel中验证数组需要键存在。删除密钥和验证通行证

时间:2018-11-13 18:13:12

标签: php laravel validation laravel-validation

我有一个items数组,在item表单键中以JSON的形式发送到控制器。

[{
    "sku": "w-hook-as1",
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
}]

此处将其转换为数组:

$request->merge(['items' => json_decode($request->items, true)]);

并根据以下规则进行了验证:

'items.*.sku' =>[
    'required',
    Rule::exists('products')->where(function ($query) {
        $query->where('company_id', Auth::user()->company_id);
    })
],

如果存在对其进行验证的数组键(假设该键已存在),则existing规则会起作用。如果我只是发送:

[{
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
}]

然后验证通过。

有没有一种方法可以检查密钥是否存在以及验证其内容?我本来希望所需的检查能够做到这一点,但是它似乎不起作用。

How to validate array in Laravel?-该答案建议验证它是否为具有x个元素的数组,但仍不检查我正在寻找的确切键。

1 个答案:

答案 0 :(得分:0)

我试图在不使用自定义规则的情况下复制您的财产,所以我要做的是:

我的刀片中有

<input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>

您可以在这里注意到,在我的第二个对象中,我的对象中没有sku项目。 然后在控制器中:

$arr = request()->merge(['items' => json_decode(request('items'), true)]);

$validator = Validator::make($arr->all(), [
   'items.*.sku' =>[
        'required'
    ]
]);

dd($validator->fails(), $validator);

响应如下:

true // this is because the validation fails.
// and the message bag contains this
#messages: array:1 [▼
  "items.1.sku" => array:1 [▼
    0 => "The items.1.sku field is required."
  ]
]

因此请确保您没有做错任何事情。

打印出$request->all(),并确保您的商品具有以下内容:

"items" => array:2 [▼
  0 => array:4 [▼
    "sku" => "w-hook-as1"
    "qty" => 2
    "cost_ex_tax" => "34.22"
    "tax_rate" => "0.2"
  ]
  1 => array:3 [▼
    "qty" => 2
    "cost_ex_tax" => "34.22"
    "tax_rate" => "0.2"
  ]
]

如果不是,那么您需要修改验证。

让我知道我是否没有按照您的步骤进行操作。