Laravel 检查旧密码,当更改新密码时

新手上路,请多包涵

我想检查用户是否将 new_password 输入作为当前密码传递,我想使用消息重定向: Your current password can't be with new password 。我怎么检查这个?我想做系统更改密码用户,但我想拒绝旧密码通过。我该怎么办?

 if (!(Hash::check($request->old_password, Auth::user()->password))) {
    return response()->json(['errors' => ['Your current password can't be with new password']], 400);
}

代码不工作。我需要将旧密码写入数据库吗?

原文由 Jadasdas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 378
2 个回答
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');
}

原文由 Mahesh Bhattarai 发布,翻译遵循 CC BY-SA 4.0 许可协议

$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);
}

您可能需要在控制器中包含以下库。

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

原文由 Jonson 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏