I want check if user pass new_password input as current password, I want to redirect with message: Your current password can't be with new password
. How I can check this? I want do system change password user, but I want denied old passwords pass. How I can do ?
if (!(Hash::check($request->old_password, Auth::user()->password))) {
return response()->json(['errors' => ['Your current password can't be with new password']], 400);
}
Code is not working. Do I need write old passwords to database?
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');
}
Hash::check
as an additional validation rule, so we have all of the error messages together, as suggested by Jonson's answer.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();
$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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With