我正在尝试验证自定义请求中的数组。如果满足两个条件,则该规则将评估为必需:
true
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;
}
您可以尝试
foreach
验证规则。$validator = Validator::make($request->all(), [
'companies.*.id' => Rule::forEach(function ($value, $attribute) {
return [
Rule::exists(Company::class, 'id'),
new HasPermission('manage-company', $value),
];
}),
]);