Laravel如何验证数组的索引和值

5
我将提交一个一维数组的值以在laravel 5.6上进行处理。
quantity[4]:11
quantity[2]:14

我需要验证索引和值,索引应该存在于股票id中,值必须是整数且最小为1。

我已经尝试过。

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

    return $rules;
}

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

你正在使用哪个版本的Laravel? - Rwd
@Ross Laravel 5.6 - Joyal
1个回答

11

我无法找到任何默认的 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;
}

主要目的是比较在查询它们的ID时使用whereIn(以减少成本)与quantityarray_keys的股票计数结果。因为quantity的索引存在于stocks中,所以$stockCntWithinArrIDs必须等于count($ids),如果不是,则至少有一个索引不是作为stocks的ID。

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

希望这可以帮助您!

编辑:

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


谢谢,你的解决方案准备好投入生产环境了吗?(只是好奇) - Joyal
1
其实,我从来没有见过这样的输入,我的意思是数组索引存在于表中,所以答案是否定的。但是在我的项目中,我写了很多自定义规则。而且我相信它可以被使用。 :D - vietanhyt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接