What is the best way to send a notification when user is locked out in Laravel Auth?

I want to send an email notification whenever a user reaches the maximum allowed login attempts (i.e. user is locked out).

What would be the best way to do this? I see a fireLockoutEvent method in the ThrottlesLogins class, should I be listening for that event? And where should I do that?

1 answer

  • answered 2018-04-14 18:44 Ben

    Yes. Create a listener for the event LockoutEvent.

    php artisan make:listener LockoutEventListener
    

    The LockoutEventListener.php is created under the folder app/Listeners/LockoutEventListener. Then register the LockoutEvent listener to the application in app/providers/EventServiceProvider.php.

    EventServiceProvider.php

    protected $listen = [
        ...
         'Illuminate\Auth\Events\Lockout' => [
            'App\Listeners\LockoutEventListener',
        ],
    ];
    

    Then update the handler method of the event LockoutEvent.

    LockoutEventListener.php

    public function handle($event)
    {
        if ($event->request->has('email')) {
            $user = User::where('email', $event->request->input('email'))->first();
            if ($user && !$attemptEmailSent) {
                Mail::to($user->email)->send(...);
            }
        }
    }