How to Compare Old Password with New Password in Laravel
In Laravel when a user tries to change his password sometimes you need to compare the old password with the new one to confirm the update.
How we do that
To do that we use the Hash class which provides the check method, it takes the old password and the new one and compares if they are the same we update if not we display an error message.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function updateUserPasswordById(Request $request, $id){
$this->validate($request,[
'current_password' => 'required|min:6',
'new_password' => 'required|confirmed|min:6'
]);
$user = User::find($id);
if(Hash::check($request->current_password, $user->password)){
$user->update([
'password' => Hash::make($request->new_password)
]);
auth()->logout();
return redirect()->route('user.login');
}
return redirect()->back()->with([
'danger' => 'Your current password does not match our records'
]);
}
}