How to add password change notification in Laravel?

1

For security reasons, in one of the applications that I'm building, whenever the user's password is changed it must be notified. To meet this goal I overwritten the method resetPassword of class ResetsPasswords in my ResetPasswordController as below:

<?php

namespace App\Http\Controllers\Auth;

//...

class ResetPasswordController extends Controller
{
    //...

    /**
     * Sobrescreve o método padrão para que seja enviada uma notificação de alteração de senha
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $user->password = Hash::make($password);

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));

        $this->guard()->login($user);

        $user->notify(new AlteracaoSenha());
    }
}

As you can see, I had to rewrite the whole method to add only one line. Is it possible to do something less around the world? Such as:

protected function resetPassword($user, $password)
{
    parent::resetPassword($user, $password);

    $user->notify(new AlteracaoSenha());
}

I understand that this example does not work there, it was just cited as an example of what I want to do.

Note: I use Laravel 5.6

    
asked by anonymous 04.04.2018 / 16:12

1 answer

1

You do not need to override the method for this because the framework itself triggers the event on the event(new PasswordReset($user)); line.

So what you need to do is create a listener for the triggered event .

In class EventServiceProvider you register a listener, for example:

protected $listen = [
    'Illuminate\Auth\Events\PasswordReset' => [
        'App\Listeners\AlteracaoSenhaNoty',
    ],
];

Then run the php artisan event:generate command to generate the AlteradaSenha class, then use the following code as an example:

<?php
namespace App\Listeners;
use Illuminate\Auth\Events\PasswordReset;

class AlteracaoSenhaNoty
{

    public function handle(PasswordReset $event)
    {
        $event->user->notify(new AlteracaoSenha());
    }
}
    
05.04.2018 / 01:32