如何在Laravel 5中验证当前,新和新密码确认?

2022-08-30 21:23:29

我已经在和中创建了密码路由,视图和方法UserController@getProfilePasswordUserController@postProfilePassword

目前,如果我填写了该字段,它将被散列并正确提交到数据库,然后我可以使用新密码登录。new_password

但是我需要能够验证并确保它们相同,并验证用户的当前密码。new_passwordnew_password_confirm

我该怎么做?

编辑:我添加到方法中,但现在我不断收到错误,即使它们确实匹配,因为我使用的是一个简单的密码。另外,我认为我需要手动检查当前密码,因为不会为我做这件事。$this->validateThe password confirmation confirmation does not match.validator

public function getProfilePassword(Request $request) {
    return view('profile/password', ['user' => Auth::user()]);
}

public function postProfilePassword(Request $request) {
    $user = Auth::user();

    $this->validate($request, [
        'old_password'          => 'required',
        'password'              => 'required|min:4',
        'password_confirmation' => 'required|confirmed'
    ]);

    $user->password = Hash::make(Input::get('new_password'));
    $user->save();
}

这就是风景

<form action="{{ route('profile/updatepassword') }}" method="post" enctype="multipart/form-data">
    <div class="form-group">
          <label for="name">Current Password</label>
          <input type="password" name="old_password" class="form-control" id="old_password">
    </div>
    <div class="form-group">
          <label for="name">Password</label>
          <input type="password" name="password" class="form-control" id="password">
    </div>
    <div class="form-group">
          <label for="name">New Password</label>
          <input type="password" name="password_confirmation" class="form-control" id="password_confirmation">
    </div>
    <button type="submit" class="btn btn-primary">Change Password</button>
    <input type="hidden" value="{{ Session::token() }}" name="_token">
 </form>

答案 1

有一个功能,允许您检查用户输入的旧密码是否正确。Hash::check()

usage

if (Hash::check("param1", "param2")) {
 //add logic here
}

param1 - user password that has been entered on the form
param2 - old password hash stored in database

如果输入了正确的旧密码,它将返回true,您可以相应地添加逻辑

为了和相同,您可以在表单请求中添加验证,例如new_passwordnew_confirm_password

'new_password' => 'required',
'new_confirm_password' => 'required|same:new_password'

答案 2

如果在整个应用程序中只需要自定义规则的功能一次,则可以使用 Closure 而不是规则对象。闭包接收属性的名称、属性的值,以及在验证失败时应调用的$fail回调

$request->validate([
    'new_password' => 'required|confirmed|min:4',
    'current_password' => ['required', function ($attribute, $value, $fail) use ($user) {
        if (!\Hash::check($value, $user->password)) {
            return $fail(__('The current password is incorrect.'));
        }
    }],
]);

https://laravel.com/docs/5.6/validation#using-closures


推荐