我尝试在我的应用中添加一项功能,允许用户更改其帐户密码。我有三个字段,我的观点如下:
<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 hook。我不知道出了什么问题,但是当我输入错误的密码时,它似乎无法验证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
}
有关于此的任何想法吗?
答案 0 :(得分:1)
根据您输入正确的旧密码时的代码,您会收到错误消息。因此,将if(Auth::attempt.....
更改为if(!Auth:attempt...
。此外,如果您使用Auth:尝试您必须再次注销用户(此方法还需要用户名或电子邮件等唯一字段来标识用户)。所以如果你使用以下方法
if (!\Hash::check($request->get('oldpassword'), \Auth::user()->password)) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
}