nameless nameless - 2 months ago 38
PHP Question

Laravel 5.3 Change Password

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
trait but how do I use it? And is there already a view as well I can use?

Can somebody help me here?


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()

        $updated = $user->update([ 'password' => bcrypt($password['new_password']) ]);

            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 :)