我需要验证一个laravel请求,就像这个stack overflow question中被接受的答案一样.但是,我的请求是一个嵌套array.我目前的代码是基于以下答案的:

    $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']返回Undefined array key.稍后将需要更改between:0,1规则,但主要关注的是验证嵌套array.

如果你对我的问题有不同的回答,那也会有帮助的.

推荐答案

您可以简单地稍微支持一下这个逻辑

$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相关问答推荐

Laravel带S3存储器

如何更改LIVE上的Filament占位符内容?

子目录中具有Vue实例的Laravel不起作用

使用MAATWebSite/EXCEL导入Exel时,不会创建Laravel模型

Laravel:通过数据透视表数据限制多对多Eager 加载

如何在Vite和Rollup中完全禁用分块?

使用 fetch api 时 Laravel 控制器不存在错误

Laravel 验证 - 不同的属性规范

使用 laravel 根据当月显示注册用户列表

Laravel查询多对多关系

在部署到 AWS 时保持我的环境参数安全

Laravel 4 定义 RESTful 控制器

使用限制排队 Guzzle 请求

在 Laravel 容器中覆盖单例

Laravel Eloquent 在子查询中有两个WHERE NOT IN

Laravel db 迁移 - renameColumn 错误 - 请求了未知的数据库类型枚举

Laravel5如何将数组传递给查看

Laravel 应用程序连接数据库时速度很慢

在 laravel 中安装 vue 3.0

Laravel 中的 isDirty() 是什么意思?