0

I am trying to execute some code when a user logs out when a session lifetime ends. But it doesn't seem to log out via the usual Logout event. Because I have the following event:

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Auth\Events\Logout;

class UserLoggedOut
{
    public function handle(Logout $event)
    {
        Log::debug("User logged out");
    }
}

and I registered it in EventServiceProvider:

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

The code works when a user logs out via the logout button and I see the message in the logs. However when the session lifetime ends and the user disconnects, it does not trigger this Lougout event.

Is there a way to make it work?

pileup
  • 1
  • 2
  • 18
  • 45
  • 2
    there is no logout when the session life ends, the session just dies, that is all that happens (there is no awareness of what is in the session) ... the session and authentication are 2 different concepts,it just happens to be that by default authentication uses the session (puts data in the session to identify the user) – lagbox May 30 '23 at 12:51
  • Oh understood. So in this case, there is no way to do anything about it? (Besides creating my own custom session handler) – pileup May 30 '23 at 12:57
  • 1
    is there a reason you need this functionality in the first place? maybe there is another way to achieve the goal – lagbox May 30 '23 at 13:04
  • Yes I added a column in the `users` table where I count how many different devices the user is logged in from, and I limit it to 5 devices. So I need to decrease the count when the session ends in some device – pileup May 30 '23 at 13:13
  • 2
    At some random time after the session cookie has expired, the session will be garbage collected. If you keep track of the session ids then you can know how many sessions are still active by checking which ones still exist. However, depending on your session driver, this may result in delay between the session expiring and actually being garbage collected. – apokryfos May 30 '23 at 13:15
  • @B.DLiroy, you can refer this: https://stackoverflow.com/questions/59031341/laravel-session-timeout-extra-logout-code/59032232#59032232 – Yasin Patel May 31 '23 at 07:24

0 Answers0