我需要验证一个 Laravel 请求,就像 stack overflow question 中接受的答案一样。 。然而我的请求是一个嵌套数组。我当前的代码基于答案:
$rules = [
'nested_array.*.variable_a' => [
'integer',
'between:0,1',
function ($attribute, $value, $fail) use ($data) {
if (!$value && !$request['variable_b']) {
$fail($attribute . ' is invalid.'); //you can customize the message here
}
}
],
'nested_array.*.variable_b' => 'integer|between:0,1',
'nested_array.*.order' => ['required', 'integer'],
];
我无法使用 !$request['variable_b']
或 !$request['nested_array.*.variable_b']
返回 未定义的数组键
。稍后需要更改 Between:0,1
规则,但主要关注的是验证嵌套数组。
如果您对我的问题有不同的方式,那也会有帮助。
最佳答案
你可以简单地回溯一下逻辑
$rules = [
'nested_array.*.variable_a' => 'integer|between:0,1',
'nested_array.*.variable_b' => 'integer|between:0,1',
'nested_array.*.order' => ['required', 'integer'],
'nested_array.*' => [
function ($attribute, $value, $fail) use ($data) {
if (!$value['variable_a'] && !$value['variable_b']) {
$fail($attribute . ' is invalid.'); //you can customize the message here
}
}
],
];
您也可以在条件中添加变量的存在
$rules = [
'nested_array.*.variable_a' => 'integer|between:0,1',
'nested_array.*.variable_b' => 'integer|between:0,1',
'nested_array.*.order' => ['required', 'integer'],
'nested_array.*' => [
function ($attribute, $value, $fail) use ($data) {
if ((!isset($value['variable_a']) || !$value['variable_a']) && (!isset($value['variable_b']) || !$value['variable_b'])) {
$fail($attribute . ' is invalid.'); //you can customize the message here
}
}
],
];
关于Laravel 验证嵌套数组请求,如果其中一个整数为零,则另一个应该大于零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75586809/