如何为嵌套的对象数组添加验证

问题描述 投票:0回答:2

我在Laravel控制器中验证我的API请求。它由一组对象组成,每个对象都需要进行验证。

我尝试了嵌套数组验证,并尝试创建一个单独的请求验证类,但无法成功。

{
    "total" : 250.00,
    "merchant_id" : 1,
    "discount" : 0,
    "items" :  {
        [id: 1, quantity: 25, notes: "some string A"],
        [id: 2, quantity: 10, notes: "some string B"],
        [id: 3, quantity: 5, notes: "some string C"]
    }
}

主对象的每个参数(total,merchant_id,discount)以及需要验证的嵌套数组参数(id,quantity,notes)

laravel
2个回答
2
投票

1
投票

我们说所有这些都是必需的。你可以像这样验证它:

$validator = Validator::make($request->all(), [
    'total' => 'required',
    'merchant_id' => 'required',
    'discount' => 'required',
    'items.*.id' => 'required',
    'items.*.quantity' => 'required',
    'items.*.notes' => 'required',
]);
© www.soinside.com 2019 - 2024. All rights reserved.