Logout Event (Laravel 7)

717 Views Asked by At

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.

2

There are 2 best solutions below

1
On
0
On

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
    }
}