Validate current user password in Laravel
1 min.
When changing a password in any system it’s good practice to verify the current one before proceeding. Here’s how to do it in Laravel — the easy way.
We will create our own custom Laravel Validator rule. Specify this extension in App/Providers/AppServiceProvider boot() method:
\Validator::extendImplicit('current_password’,
function($attribute, $value, $parameters, $validator)
{
return \Hash::check($value, auth()->user()->password);
});
Using extendImplicit() means that the rule will be applied even if the passed attribute is empty or does not exist. If you do not need that for some reason, then just use extend() method instead — this way the rule will be skipped for non-present or empty attributes.
Now you can use this rule as any other in your usual validation process:
$this->validate($request, [
'name’ => 'required|max:255’,
'email’ => 'required|email|max:255|unique:users,email,'. $user->id,
'current_password’ => 'current_password’,
'new_password’ => 'min:6|confirmed’,
]);