【问题标题】:Use Laravel "distinct" validation rule but ignore some array entries based on an array property使用 Laravel “distinct” 验证规则,但忽略一些基于数组属性的数组条目
【发布时间】:2019-11-20 12:19:41
【问题描述】:

我想在 Laravel 中使用表单请求来验证输入数据数组。 数组如下所示:

[
  'issues' =>
  [
     'type' => 'prio_1',
     'note' => 'This is some text'
  ],
  [
     'type' => 'prio_2',
     'note' => 'This is some other text'
  ]
  [
     'type' => 'prio_1',
     'note' => 'This is yet some other text',
     'deleted' => true
  ]
]

我想验证该数组中的type 字段是distinct,考虑到第三个数组条目是deleted,因此需要忽略此规则。 使用

["issues.*.type" => 'required|distinct']

当然不起作用,因为如果数组属性具有特定值,则无法参数化此规则以忽略该规则。 过滤输入以忽略已删除的条目也不是一种选择,因为在响应中替换 * 的索引需要与请求中的原始索引匹配。

有没有办法扩展distinct 规则(使用自定义验证器)以允许这种验证?或者任何其他方式允许这样做?

【问题讨论】:

    标签: arrays laravel validation laravel-5 distinct


    【解决方案1】:

    您可以使用closurecollection 来检查是否有重复项(不包括“已删除”项):

    public function rules()
    {
        return [
            "issues.*.type" => [
                'required', function ($attr, $value, $fail) {
                    $count = collect($this->input('issues'))
                        ->reject(function ($item) {
                            return isset($item['deleted']) && $item['deleted'];
                        })
                        ->filter(function ($item) use ($value) {
                            return $item['type'] === $value;
                        })
                        ->count();
    
                    if ($count > 1) {
                        $fail(__('validation.distinct'));
                    }
                },
            ],
        ];
    }
    

    为了提高效率,您也可以只计算之前的值,然后检查计数是否大于一:

    public function rules()
    {
        $duplicateTypes = collect($this->input('issues'))
            ->reject(function ($item) {
                return isset($item['deleted']) && $item['deleted'];
            })
            ->groupBy('type')
            ->map->count();
    
        return [
            "issues.*.type" => [
                'required', function ($attr, $value, $fail) use($duplicateTypes) {
                    if ($duplicateTypes[$value] > 1) {
                        $fail(__('validation.distinct'));
                    }
                },
            ],
        ];
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-23
      • 2017-07-09
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多