如何访问 Rule::requiredIf() 验证中的嵌套项

How to access nested item in Rule::requiredIf() validation

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

  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

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

[
    '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;
}