3

I'm pretty new to Laravel and was wondering how I can set up a function to run on an event. Specifically, when a user log outs, how can I call a function?

What would be the best way to do this, registering a new logout event or does Laravel 7 already have a file I can edit to run commands on logout?

Thanks for any help.

GTS Joe
  • 3,612
  • 12
  • 52
  • 94

2 Answers2

0

You can listen for the Illuminate\Auth\Events\Logout event.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • 1
    However, it should be noted that things like session expiration or closing the browser window will not generate one of these events. If you're looking to do something like "who's online" lists, you need a different approach like websockets. – ceejayoz Jul 13 '20 at 16:29
0

There is indeed already a logout Event defined that gets fired when a user logs out. It is located at Illuminate\Auth\Events\Logout.

You need to create a new event Listener, then tell Laravel to have that listener subscribe to the Logout event, by adding the mapping to EventServiceProvider.php like so:

class EventServiceProvider extends ServiceProvider
{

    protected $listen = [
        ...
        Logout::class => [
            'App\Listeners\HandleLogout',
        ],
        ...
    ];
   
    ...

Then you can make a Listener class in app/Listeners as follows:

LogoutHandler.php

class LogoutHandler
{
    /**
     * Handle the event.
     *
     * @param  Logout  $event
     * @return void
     */
    public function handle(Logout $event)
    {
        $event->user; // The user that logged out
        #event->guard; // The auth guard used
    }
}

Kurt Friars
  • 3,625
  • 2
  • 16
  • 29