How to add password exchange notification in Laravel?

Asked

Viewed 178 times

1

For security reasons, in one of the applications I am building, whenever the user’s password is changed this must be notified. To meet this goal I override the method resetPassword 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 can be seen, I had to rewrite the entire method to add only one line. Is it possible to do something less around the world? Just as:

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

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

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

Note: I use Laravel 5.6

1 answer

2

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

So what you need to do is create a Listener for the event fired.

In class EventServiceProvider you register a Istener, for example:

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

Then execute the command php artisan event:generate to generate the class AlteradaSenha, 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());
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.