在Laravel中制作Ardent,不需要保存新密码
I'm doing user editing facility for my admin panel. I want to ignore empty password on update, but not on create.
I have following validation rules for User model:
public static $rules = array(
'login' => 'required|max:255|alpha_dash|unique',
'displayname' => 'required|max:255|unique',
'email' => 'required|email|max:255|unique',
'password' => 'required|confirmed',
'password_confirmation' => 'required',
);
But it doesn't let me update user model when I don't pass password to it. It just complains about not having a password.
How to make it work?
我正在为我的管理面板进行用户编辑工具。 我想在更新时忽略空密码,但不想在创建时忽略。 p>
我有以下用户模型的验证规则: p>
public static $ rules = array(
'login'=>'required | max:255 | alpha_dash | unique',
'displayname'=>'required | max:255 | unique',
'email'=&gt ;'required | email | max:255 | unique',
'password'=>'required | confirmed',
'passate_confirmation'=>'required',
);
code>
但是当我不向其传递密码时,它不允许我更新用户模型。 它只是抱怨没有密码。 p>
如何使它工作? p>
div>
You can do something like this in your controller:
if ($user->exists)
{
$user::$rules['password'] = (Input::get('password')) ? 'required|confirmed' : '';
$user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}
$user->save();
That's something people are still thinking about. But usually create rules and update rules will be different.
public static $create_rules = array(
'login' => 'required|max:255|alpha_dash|unique',
'displayname' => 'required|max:255|unique',
'email' => 'required|email|max:255|unique',
'password' => 'required|confirmed',
'password_confirmation' => 'required',
);
public static $update_rules = array(
'login' => 'required|max:255|alpha_dash|unique',
'displayname' => 'required|max:255|unique',
'email' => 'required|email|max:255|unique',
);
Then in your validation code, you can
if ( ! $this->exists || Input::get('password'))
{
$validation_rules = static::$create_rules;
}
else
{
$validation_rules = static::$update_rules;
}
If you want to consolidate this behavior to the model itself (so it doesn't matter where it's being created/saved from) you can utilize Ardent's beforeValidate
function to change the rules before validating:
public function beforeValidate()
{
if(isset($this->id))
{
self::$rules['password'] = 'confirmed';
self::$rules['password_confirmation'] = '';
}
}
You would just add code like that anywhere in the model in question.