Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

adense's avatar

Listener to clear session on logout - not working

I want to put a Listener in my Laravel project which listens for the user logging out and fires and event then, for an example a redirect or clearing the session.

I have this code which I added to the EventServiceProvider.php:

<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
            'App\Listeners\EventListener',
        ],
        'App\Listeners\Logout' => [
            'App\Listeners\ClearSessionAfterUserLogout'
        ],
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);

        //
    }

}

Then, I have following code put inside my app/Listeners/ClearSessionAfterUserLogout:

<?php
namespace App\Listeners;
use Session;
use App\Classes\Helper;

class ClearSessionAfterUserLogout{
    public function handle(Logout $event){
        Session::flush();
        Session::set('configuration', NULL);
        Helper::unloadConfiguration();
        return redirect('/');
    }
}
?>

Nothing I put inside my ClearSessionAfterUserLogout seems to be working. The function "unloadConfiguration()" I know for a fact works, because I use it in other places. (It simply clears a specified Session variable). Flushing the session does nothing either. Because when I login with another account, some content is STILL loaded based on what was in the session for the previous account.

So my question: How do I clear all session data when the user logs out?

0 likes
0 replies

Please or to participate in this conversation.