【问题标题】:laravel how to validate array index and valueslaravel如何验证数组索引和值
【发布时间】:2018-11-14 14:14:29
【问题描述】:

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

quantity[4]:11
quantity[2]:14

我必须验证指数和价值,指数应该作为股票退出,id 和 value 必须是整数且最小为 1

我试过了

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

    return $rules;
}

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

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • @Ross Laravel 5.6

标签: php laravel laravel-5 laravel-validation


【解决方案1】:

我看不到任何可以使用默认 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;
}

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

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

希望对您有所帮助!

已编辑:

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

【讨论】:

  • 谢谢,您的解决方案准备好用于生产环境了吗? (只是好奇)
  • 其实我从来没有见过这样的输入,我的意思是数组索引存在于一个表中,所以,答案是否定的。但是我之前在项目中写了很多自定义规则。而且我相信它可以使用。 :D
猜你喜欢
  • 2023-03-17
  • 2013-08-01
  • 2021-05-12
  • 2020-09-20
  • 2019-12-18
  • 2021-10-29
  • 2018-06-08
  • 2017-09-25
  • 1970-01-01
相关资源
最近更新 更多