我试图在我的应用程序中注册一个用户,同时将所有业务逻辑保留在模型中,并尽可能少地保留在 Controller 中。为实现这一点,当 Class::creating()
事件触发时,我在模型的 boot()
方法中运行用户验证。如果验证失败,我只返回 false,取消事件。你可以在这里看到:
public static function boot() {
parent::boot();
User::creating(function(){
$validator = new Services\Validators\RUser;
if (! $validator->passes()) return false;
});
}
您看到的验证器类只是规则,它包含一个 getErrors()
函数。
我的问题是,我如何重写它以便我可以检索验证器的错误以便稍后在条件重定向中使用?
我的 Controller postRegister()
(单击表单上的提交时调用的函数)如下所示:
public function postRegister() {
$user = new User(Input::all());
$user->save();
}
我知道我没有在 Controller 中正确处理它,所以我也希望能得到一些建议。
谢谢。
最佳答案
你会设置一个'protected $errors;' User 模型上的属性,然后是
User::creating(function(){
$validator = new Services\Validators\RUser;
if (! $validator->passes()) {
$this->errors = $validation->getErrors();
return false;
}
});
关于php - (Laravel) 如何从用户模型中获取验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888895/