原来 User 模块做起来并没有那么容易。
首先验证是否登陆,Laravel 的 middleware 真的很强大:
1 2 3 4 |
public function __construct() { $this->middleware('auth'); } |
然后设定好 Validator,用户要先输入原密码,然后输入两次新密码:
1 2 3 4 5 6 7 |
protected function validator(array $data) { return Validator::make($data, [ 'old_password' => 'required|min:6', 'new_password' => 'required|confirmed|min:6', ]); } |
接着建立一个 function 去处理用户密码,这里用到了 hash facade,新密码直接 bcrypt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public function ChangePassword(Request $request) { // $validator = $this->validator($request->all()); if ($validator->fails()) { $this->throwValidationException( $request, $validator ); }else{ $user=Auth::user(); $match=false; $old_password=$request->old_password; $new_password=$request->new_password; $user_password=$user->password; if (Hash::check($old_password,$user_password)){ $match=true; }else{ return redirect()->back()->withErrors('The old password is incorrect'); } if($match==true){ $user->password=bcrypt($new_password); $user->save(); return redirect()->action('UserProfileController@index')->with('success','User password updated.') ->with('success_update_password',true); } } } |
这里的 with 会建立起一个一次性的 session,我新建了一个 success.blade.php 去跟它对接:
1 2 3 4 5 6 7 8 9 10 |
@if (session('success')) <!-- Toastr script --> <script src="/js/plugins/toastr/toastr.min.js"></script> <script type="text/javascript"> $(document).ready(function() { toastr.success('{{session('success')}}','Success'); }); </script> @endif |
这样成功更改密码之后就会有一个更改成功的提示。
如果 old password 对不上的话,则是出现错误提示框。