我正在尝试在我的应用程序中添加一个功能,允许用户更改帐户密码。我有三个字段,我的视图如下:
<form class="form" role="form" action="{{ url('users/updatePassword') }}" method="post">
{{ csrf_field() }}
<div class="form-group label-floating {{ $errors->has('oldpassword') ? 'has-error' : '' }}">
<label class="control-label" for="oldpassword">Old Password</label>
<input type="password" name="oldpassword" class="form-control">
@if ($errors->has('oldpassword'))
<span class="help-block">
<strong>{{ $errors->first('oldpassword') }}</strong>
</span>
@endif
</div>
<div class="form-group label-floating {{ $errors->has('newpassword') ? 'has-error' : '' }}">
<label class="control-label" for="newpassword">New Password</label>
<input type="password" name="newpassword" class="form-control">
@if ($errors->has('newpassword'))
<span class="help-block">
<strong>{{ $errors->first('newpassword') }}</strong>
</span>
@endif
</div>
<div class="form-group label-floating">
<label class="control-label" for="newpassword_confirmation">Confirm Password</label>
<input type="password" name="newpassword_confirmation" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-raised btn-primary">Change</button>
</div>
</form>
首先,我想检查是否所有字段都已完全填充,为此我使用了Validator
。然后从数据库中检查oldpassword
是否匹配,所以我使用if (Auth::attempt(array('password' => $request->oldpassword)))
条件。我还在laravel 5.2文档中发现了After Validation钩子。我不知道出了什么问题,但当我键入错误的密码时,它似乎无法验证oldpassword
字段。
我的控制器:
$validator = Validator::make($request->all(), [
'oldpassword' => 'required|max:255',
'newpassword' => 'required|min:6|max:255|confirmed',
]);
$validator->after(function($validator) use($request) {
if (Auth::attempt(array('password' => $request->oldpassword))) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
}
});
if ($validator->fails()) {
// Toastr
$title = "Oops!";
$message = "Please make sure to fill all required fields.";
$options = [
'progressBar' => false,
'positionClass' => 'toast-top-right',
'timeOut' => 6000,
];
Toastr::error($message, $title, $options);
return redirect()->back()
->withErrors($validator);
} else {
return 'success'; // for testing only
}
对此有什么想法吗?
根据您的代码,当您输入正确的旧密码时,您会收到错误。因此,将if(Auth::attempt.....
更改为if(!Auth:attempt...
。此外,如果您使用Auth:atry,则必须再次注销用户(此方法还需要用户名或电子邮件等唯一字段来识别用户)。所以最好使用以下方法
if (!'Hash::check($request->get('oldpassword'), 'Auth::user()->password)) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
}