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

问题描述 投票:0回答:2

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

  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
php arrays laravel validation rules
2个回答
2
投票

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

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

0
投票

您可以尝试

foreach
验证规则
这是文档中的示例:

$validator = Validator::make($request->all(), [
    'companies.*.id' => Rule::forEach(function ($value, $attribute) {
        return [
            Rule::exists(Company::class, 'id'),
            new HasPermission('manage-company', $value),
        ];
    }),
]);
© www.soinside.com 2019 - 2024. All rights reserved.