php - 如何在 Laravel 自定义验证中获取其他字段值

标签 php laravel validation

我正在使用自定义验证规则来验证从文件中读取的一些数据。规则如下:

$this->rules = [
            'file_data'          => 'required|array',
            'file_data.*.id'     => 'required',
            'file_data.*.name'   => 'required',
            'file_data.*.code'   => 'required|code_exists' 
        ];

并应用这些规则,例如

$validationResult = validator($data, $this->rules, $customMessageArray);

code_exists 中,我需要 id 的值来运行验证。我试图通过 $parameters 传递值,例如 code_exists:id,但它在参数数组中为我提供了字符串 id。我怎样才能传递实际值?

最佳答案

您应该获取数组的键,然后获取 id。像这样:

'file_data.*.code' => [
    'required',
    function($attribute, $value, $fail) use ($data) {
        $index = explode('.', $attribute)[1];
        $id = data_get($data, "file_data.$index.id");

        $isExists = DB::table('table_name')->whereId($id)->whereCode($value)->exists();
        if (!$isExists) {
            return $fail(__('validation.exists', ['attribute' => $attribute]));
        }
   }
],

关于php - 如何在 Laravel 自定义验证中获取其他字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674238/

相关文章:

c# - 判断一个字符串是否包含有效的javascript代码

java - Java 小程序加载失败时如何显示消息?

php - 为什么即使用户存在,MySQL 总是给出拒绝访问的错误?

php - Laravel - 带有未签名主键的表迁移错误

php - 使用 Laravel 进行正确的测试流程?

jQuery 验证插件复选框 errorPlacement

文件上传验证

php - Laravel Passport 在收到访问 token 后不验证用户身份

php - 如果数组中已经存在值,则在 PHP 中发出错误

php - Laravel 和 Blade 错误