【问题标题】:Validating array in laravel requires the key to exist. Remove the key and validation passes在 laravel 中验证数组需要密钥存在。删除密钥和验证通过
【发布时间】:2023-04-04 11:36:01
【问题描述】:

我有一个 items 数组,在 items 表单键中作为 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);
    })
],

如果验证所针对的数组键存在,则存在规则确实有效,假设该键存在。如果我只是发送:

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

然后验证通过。

有没有一种方法可以检查密钥是否存在以及验证其内容?我原以为所需的检查会执行此操作,但它似乎不起作用。

How to validate array in Laravel? - 这个答案建议验证它是一个包含 x 个元素的数组,但仍然没有检查我正在寻找的确切键是否存在。

【问题讨论】:

    标签: php laravel validation laravel-validation


    【解决方案1】:

    我试图在没有自定义规则的情况下复制你所拥有的,所以我所做的如下:

    在我的刀片中,我有

    <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-&gt;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"
      ]
    ]
    

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

    如果我没有按照您执行的某些步骤,请告诉我。

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 2015-05-19
      • 2014-05-14
      • 1970-01-01
      相关资源
      最近更新 更多