【问题标题】:How to access nested item in Rule::requiredIf() validation如何在 Rule::requiredIf() 验证中访问嵌套项
【发布时间】:2021-09-30 01:29:57
【问题描述】:

我正在尝试验证自定义请求中的数组。如果满足两个条件,则该规则评估为 required:

  1. 属性3是true
  2. 同一数组中的另一列是true

这就是我正在做的事情:

public function rules()
{
    return [
        'attribute1' => 'required',
        'attribute2' => 'required',
        'attribute3' => 'required',
        ...
        'attribute10.*.column3' => Rule::requiredIf(fn() => $this->attribute3), // <- array
        'attribute10.*.column4' => Rule::requiredIf(fn() => $this->attribute3), // <- array
        'attribute10.*.column5' => Rule::requiredIf(fn() => $this->attribute3), // <- array
    ];
}

我真正需要的是这个:

'attribute10.*.column4' => Rule::requiredIf(fn($item <- magically hint this currently looped item) => $this->attribute3 && $item->column2 <- so I can use it like this), // <- array

【问题讨论】:

  • 你能分享一个传入请求的例子吗?您可以在返回之前在 FormRequest 的规则函数中执行 Log::debug($this-&gt;all());,然后检查 laravel 日志以查看请求中到达的内容。
  • @porloscerrosΨ - 我不想分享,因为这是公司的隐私,而且代码不是开源的。但信息是相同的 - 我收到一个数组,当根据规则检查时,我只想访问它的当前项目。
  • 好的,我发布了一个假设请求结构的答案。也许你必须适应它,但你有一个想法
  • 前段时间我回答了另一个问题,它不一样,但你可以根据你的要求调整它的想法stackoverflow.com/a/59198620/7498116

标签: laravel validation


【解决方案1】:

假设传入的请求具有如下结构:

[
    'attribute1' => 1,
    'attribute2' => 0,
    'attribute3' => 1,
    'attribute10' => [
        [
            'column1' => 1,
            'column2' => 1,
            'column3' => 0,
        ],
        [
            'column1' => 0,
            'column2' => 1,
            'column3' => 0,
        ],
    ],
]

您可以将规则数组设置为一个变量,然后循环遍历attribute10 字段数组元素并在规则变量上合并每个规则。然后,您将可以访问嵌套数组中的其他元素。
即:

public function rules()
{
    $rules = [
        'attribute1' => 'required',
        'attribute2' => 'required',
        'attribute3' => 'required',
    ];
    foreach($this->attribute10 as $key => $item) {
        array_merge($rules, [
            'attribute10.'.$key.'.column2' => Rule::requiredIf($this->attribute3 && $item['column1']),
            'attribute10.'.$key.'.column3' => Rule::requiredIf($this->attribute3 && $item['column2']),
            //...
        ]);
    }
    return $rules;
}

【讨论】:

  • 谢谢,我试试这个!
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多