duanfu5239 2016-11-12 15:00
浏览 67
已采纳

Laravel 5.3更改密码

I'm building a Laravel 5.3 app and using the basic auth of laravel (artisan make:auth). Now, the "Forgot Password" functionality works fine, so if a user can't login because he doesn't know his password, he can get a mail to reset it. But now I want that logged in users can change their password as well. I found that, but this doesn't really help me. I also know that there's a ResetsPasswords trait but how do I use it? And is there already a view as well I can use?

Can somebody help me here?

  • 写回答

2条回答 默认 最新

  • douziqian2871 2016-11-12 16:55
    关注

    You don't actually need to use the default password controller to achieve this, you can write your own function to get the same result, for example:

    public function postUpdatePassword() {
    
            $user = Auth::user();
    
            $password = $this->request->only([
                'current_password', 'new_password', 'new_password_confirmation'
            ]);
    
            $validator = Validator::make($password, [
                'current_password' => 'required|current_password_match',
                'new_password'     => 'required|min:6|confirmed',
            ]);
    
            if ( $validator->fails() )
                return back()
                    ->withErrors($validator)
                    ->withInput();
    
    
            $updated = $user->update([ 'password' => bcrypt($password['new_password']) ]);
    
            if($updated)
                return back()->with('success', 1);
    
            return back()->with('success', 0);
        }
    

    As you can see I registered a new custom validation rule to check if the new passowrd match the old one, to register the rule just go to "app/Providers/AppServiceProvider.php" and add to the boot function the next lines:

    Validator::extend('current_password_match', function($attribute, $value, $parameters, $validator) {
                return Hash::check($value, Auth::user()->password);
            });
    

    Now the validation rule works but you won't get the error message, to add an error message to the new rule you just created you will have to modify these lines in "resources/lang/en/validation.php":

    'custom' => [
            'current_password' => [
                'current_password_match' => 'Current password is incorrect.',
            ],
        ],
    

    That's it, now you can use this function to change your the current user password :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?