(Laravel) 如何从用户模型中获取验证错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20888895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Laravel) How can I get validation errors from User model?
提问by Gadoma
I'm trying to register a user in my application while keeping all business logic in the model and as little as possible in the controller. To accomplish this, I'm running user validation in the model's boot()
method when the Class::creating()
event fires. If the validation fails, I simply return false, cancelling the event. You can see this here:
我试图在我的应用程序中注册用户,同时将所有业务逻辑保留在模型中,并尽可能少地保留在控制器中。为了实现这一点,我boot()
在Class::creating()
事件触发时在模型的方法中运行用户验证。如果验证失败,我只是返回 false,取消事件。你可以在这里看到这个:
public static function boot() {
parent::boot();
User::creating(function(){
$validator = new Services\Validators\RUser;
if (! $validator->passes()) return false;
});
}
The validator class you see is simply rules and it contains a getErrors()
function.
您看到的验证器类只是规则,它包含一个getErrors()
函数。
My question is, how can I rewrite this so that I can retrieve the validator's errors for use in a conditional redirect later?
我的问题是,我怎样才能重写它,以便我可以检索验证器的错误,以便稍后在条件重定向中使用?
My controller postRegister()
(the function called when clicking submit on form) looks like this:
我的控制器postRegister()
(单击表单提交时调用的函数)如下所示:
public function postRegister() {
$user = new User(Input::all());
$user->save();
}
I know I'm nothandling that in the controller correctly, so I would appreciate some advice with that as well.
我知道我没有在控制器中正确处理它,所以我也希望得到一些建议。
Thanks.
谢谢。
回答by bgallagh3r
You would set a 'protected $errors;' property on the User model, and then
你会设置一个'protected $errors;' User 模型上的属性,然后
User::creating(function(){
$validator = new Services\Validators\RUser;
if (! $validator->passes()) {
$this->errors = $validation->getErrors();
return false;
}
});
回答by Gadoma
Not a direct answer to your question, but you should check out the Ardent package which is great for automatic model validation and has some other nice accompanying features. Internally it uses native Laravel validators so it's easy to use and will do just what you ask about. It really saves a lot of work (DRY) and I find it very useful.
不是您问题的直接答案,但您应该查看 Ardent 包,它非常适合自动模型验证,并且具有其他一些不错的附带功能。在内部,它使用本地 Laravel 验证器,因此它易于使用并且会按照您的要求执行。它确实节省了大量工作(DRY),我发现它非常有用。
https://github.com/laravelbook/ardent
https://github.com/laravelbook/ardent
The basics from the docs:
文档中的基础知识:
Ardent models use Laravel's built-in Validator class. Defining validation rules for a model is simple and is typically done in your model class as a static variable:
Ardent 模型使用 Laravel 的内置 Validator 类。为模型定义验证规则很简单,通常在模型类中作为静态变量完成:
class User extends \LaravelBook\Ardent\Ardent {
public static $rules = array(
'name' => 'required|between:4,16',
'email' => 'required|email',
'password' => 'required|alpha_num|between:4,8|confirmed',
'password_confirmation' => 'required|alpha_num|between:4,8',
);
}
Ardent models validate themselves automatically when Ardent->save() is called. You can also validate a model at any time using the Ardent->validate() method.
当 Ardent->save() 被调用时,Ardent 模型会自动验证自己。您还可以随时使用 Ardent->validate() 方法验证模型。
$user = new User;
$user->name = 'John doe';
$user->email = '[email protected]';
$user->password = 'test';
$success = $user->save(); // returns false if model is invalid
When an Ardent model fails to validate, a Illuminate\Support\MessageBag object is attached to the Ardent object which contains validation failure messages.
Retrieve the validation errors message collection instance with Ardent->errors() method or Ardent->validationErrors property.
Retrieve all validation errors with Ardent->errors()->all(). Retrieve errors for a specific attribute using Ardent->validationErrors->get('attribute').
当 Ardent 模型无法验证时,Illuminate\Support\MessageBag 对象会附加到包含验证失败消息的 Ardent 对象。
使用 Ardent->errors() 方法或 Ardent->validationErrors 属性检索验证错误消息集合实例。
使用 Ardent->errors()->all() 检索所有验证错误。使用 Ardent->validationErrors->get('attribute') 检索特定属性的错误。
So in the end you can do:
所以最后你可以这样做:
$user = new User;
$user->name = 'John doe';
$user->email = '[email protected]';
$user->password = 'test';
if(!$user->save())
{
print_r($user->errors()->all()); //or whatever else you wish to do on failure
}
回答by Lee
I installed Laravel for the first time less than 12 hours ago, so i may be acting a little prematurely, but to my knowledge...
我在不到 12 小时前第一次安装了 Laravel,所以我的行为可能有点过早,但据我所知......
You have two main options, return the validator class, or store the errors in the User model. I'm currently working with the former, so i have a validate() method which returns the Validator class, which i then do the if($v->passes())
in my controller and can output errors in the controller via $v->messages()
.
您有两个主要选项,返回验证器类,或将错误存储在 User 模型中。我目前正在使用前者,所以我有一个 validate() 方法,它返回 Validator 类,然后我if($v->passes())
在我的控制器中执行该类,并且可以通过$v->messages()
.
Using your method, you will want to store your errors in the User object if you want to continue returning false on failure. So you could change:
使用您的方法,如果您想在失败时继续返回 false,您将需要将错误存储在 User 对象中。所以你可以改变:
if (! $validator->passes()) return false;
to
到
if (! $validator->passes()) {
$this->errors = $validator->messages();
return false;
}
and in your controller do:
并在您的控制器中执行以下操作:
if(isset($user->errors)) {
//loop and print errors from validator
}
N.B: just to reiterate, im a complete newbie to laravel so i may have gotten something completely wrong. But if i have, someone will correct me and we'll both have learned something :)
注意:只是重申一下,我是 Laravel 的完全新手,所以我可能完全错误。但如果我有,有人会纠正我,我们都会学到一些东西:)