Laravel check for old password, when change new password

$validator = Validator::make($request->all(), [
    'old_password' => [
        'required', function ($attribute, $value, $fail) {
            if (!Hash::check($value, Auth::user()->password)) {
                $fail('Old Password didn\'t match');
            }
        },
    ],
]);

if($validator->fails()) {
    return redirect()->back()->withInput()->withErrors($validator);
}

You may need to include the following libraries in your controller.

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

  • The accepted answer is fine. But it's better to have the Hash::check as an additional validation rule, so we have all of the error messages together, as suggested by Jonson's answer.
  • However, since our custom validation is part of the rules array, we don't need to use Validator::make.

This is a solution based on both answers:

$user = auth()->user();
        
$validated = $request->validate([
    'current_password' => [
        'required',
        
        function ($attribute, $value, $fail) use ($user) {
            if (!Hash::check($value, $user->password)) {
                $fail('Your password was not updated, since the provided current password does not match.');
            }
        }
    ],
    'new_password' => [
        'required', 'min:6', 'confirmed', 'different:current_password'
    ]
]);

$user->fill([
    'password' => Hash::make($validated['new_password'])
])->save();

$request->session()->flash('notification', 'Your password has been updated successfully.');

return back();

use Illuminate\Support\Facades\Hash;
$user = User::findOrFail($id);

/*
* Validate all input fields
*/
$this->validate($request, [
    'password' => 'required',
    'new_password' => 'confirmed|max:8|different:password',
]);

if (Hash::check($request->password, $user->password)) { 
   $user->fill([
    'password' => Hash::make($request->new_password)
    ])->save();

   $request->session()->flash('success', 'Password changed');
    return redirect()->route('your.route');

} else {
    $request->session()->flash('error', 'Password does not match');
    return redirect()->route('your.route');
}

Tags:

Php

Laravel