【问题标题】:How to pass additional parameters to validator->after function in Laravel 8.x?如何在 Laravel 8.x 中将附加参数传递给验证器-> 后函数?
【发布时间】:2022-01-21 10:51:28
【问题描述】:

我使用的是 Laravel 8.x 版本。

正如我们所知,我们还可以附加回调以在验证完成后运行。这使我们能够轻松地执行进一步的验证,甚至可以将更多错误消息添加到消息集合中。我们可以在validator 实例上调用after 方法:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add(
            'field', 'Something is wrong'
        );
    }
});

if ($validator->fails()) {
    //
}

但我想在这个after 函数中使用$customVariable,例如:

$validator = Validator::make(...);

$customVariable = 'not happy';

$validator->after(function ($validator, $customVariable) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add(
            'field', 'Something is wrong because you are ' . $customVariable
        );
    }
});

if ($validator->fails()) {
    //
}

有没有人可以建议我如何在$validator->after() 函数中传递和使用自定义变量/参数?谢谢。

【问题讨论】:

    标签: php validation laravel-8


    【解决方案1】:

    您可以使用 use 关键字 (docs) 从父作用域继承变量。这样的事情应该可以工作:

    $validator = Validator::make(...);
    
    $customVariable = 'not happy';
    
    $validator->after(function ($validator) use ($customVariable) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add(
                'field', 'Something is wrong because you are ' . $customVariable
            );
        }
    });
    
    if ($validator->fails()) {
        //
    }
    

    【讨论】:

    • 谢谢亲爱的@szaman szaman。这类似于我们使用多个orWhere 条件并想要传递条件参数时。你的解决方案奏效了。谢谢:)
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多