Make Ardent in Laravel not requiring new password on save
Question
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?
Solution
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();
OTHER TIPS
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.