其中oldpassword是每个表单的里的name值,所以在使用after方法添加自定义错误的时候 $validator->errors()->add('oldpassword', '原密码错误');中,oldpassword一定要写对是在哪个表单的错误,这样才能正确的显示。
6、完成后的示例
UserController
public function getReset() { return view('auth.reset'); } public function postReset(Request $request) { $oldpassword = $request->input('oldpassword'); $password = $request->input('password'); $data = $request->all(); $rules = [ 'oldpassword'=>'required|between:6,20', 'password'=>'required|between:6,20|confirmed', ]; $messages = [ 'required' => '密码不能为空', 'between' => '密码必须是6~20位之间', 'confirmed' => '新密码和确认密码不匹配' ]; $validator = Validator::make($data, $rules, $messages); $user = Auth::user(); $validator->after(function($validator) use ($oldpassword, $user) { if (!\Hash::check($oldpassword, $user->password)) { $validator->errors()->add('oldpassword', '原密码错误'); } }); if ($validator->fails()) { return back()->withErrors($validator); //返回一次性错误 } $user->password = bcrypt($password); $user->save(); Auth::logout(); //更改完这次密码后,退出这个用户 return redirect('/login'); }
reset.blade
<form action="" method="post"> <h3>修改密码</h3> @if($errors->first()) <div> <button data-close="alert"></button> <span> </span> </div> @endif {!! csrf_field() !!} <div> <label>原始密码</label> <input type="password" autocomplete="off" placeholder="Old Password"> </div> <div> <label>新密码</label> <input type="password" autocomplete="off" placeholder="New password"> </div> <div> <label>重复密码</label> <input type="password" autocomplete="off" placeholder="Repeat password"> </div> <div> <button type="submit">确定</button> </div> </form>