laravel如何验证数组索引和值

Joy*_*yal 2 php laravel laravel-5 laravel-validation

我正在提交一维值数组以在laravel 5.6上处理

quantity[4]:11
quantity[2]:14
Run Code Online (Sandbox Code Playgroud)

我必须同时验证索引和值,索引应作为股票退出,id和值必须为整数且最小值为1

我试过了

public function rules()
{
    $rules = [
       'quantity.*' => 'exists:stocks,id',
       'quantity' => 'required|integer|min:1',
    ];

    return $rules;
}
Run Code Online (Sandbox Code Playgroud)

但是它仅验证值而不是索引,请分享您的想法和评论。

vie*_*hyt 5

我看不到任何可以使用默认Laravel验证来验证数组索引的地方。这就是为什么我们需要编写一个自定义的。

public function rules()
{
    $rules = [
       'quantity.*' => 'required|integer|min:1',
       'quantity' => [
           'required',
           'min:1', // make sure the input array is not empty <= edited
           'array',
           function($attribute, $value, $fail) {
               // index arr
               $ids = array_keys($value);
               // query to check if array keys is not valid
               $stockCntWithinArrIDs = StockModelFullNameWhaterver::whereIn('id', $ids)->count();
               if ($stockCntWithinArrIDs != count($ids))
                   return $fail($attribute.' is invalid.');  // -> "quantity is invalid"
           }
       ],
    ];

    return $rules;
}
Run Code Online (Sandbox Code Playgroud)

要点是在查询whereIn(以降低成本)其id与array_keys 时比较库存计数结果quantity。由于quantity的索引存在于中stocks$stockCntWithinArrIDs因此必须等于count($ids),如果不存在,则至少有一个索引不作为stocksid。

您可以使用foreach ($ids)然后查询相应的内容stock以查看我的解决方案是否有效。但是请不要在生产环境中使用该解决方案。:D

希望有帮助!

编辑:

参见:https : //laravel.com/docs/5.6/validation#custom-validation-rules