skip to Main Content

In my Laravel application, I set the login session settings and set

'expire_on_close' => true

in config/session.php file so that if the user closes the browser, his session ends, and I also record when the user logged in for the last time in my table
How can I know if the session ended or when the user’s session ended when he closed the browser or forgot the browser to open and the session time specified in the lifetime option in the config/session.php file expired.

Are there events that are executed in Laravel when the session is closed?
and how to use this event. Knowing that my Laravel application is multi-tenant manually and each tenant has a separate database connection and I want to record the user’s session expiration time in the database of the tenant that owns this user

2

Answers


  1. It is impossible to know when the user ended the session without having the user or the user’s browser trigger an event, eg: the user clicks ‘logout’ or some JS hooks into a "window closed" event.

    Aside from that it is either:

    1. The user-side cookie expiring, which can and will most likely happen outside the scope of the user actually having your website open.
    2. The session will expire server-side which will not trigger any event either, unless you override the default session cleanup behaviour. Even so, the time that this happens is unlikely to correspond with the actual session expiration, just some arbitrary time afterwards.

    TLDR: There is no reliable way to know when a user stops looking at your website, nor trigger an event on session expiration.

    The best that you can reasonably do is track a "last active" time and make an assumption that after X minutes the user is no longer active.

    Login or Signup to reply.
  2. In Laravel, the session termination due to browser close (when ‘expire_on_close’ => true is set) or expiration does not have a direct event you can listen to out of the box. The session expiry is essentially a client-side occurrence; the server doesn’t exactly "know" when the user’s browser is closed.

    However, you can employ some techniques to estimate or work around this.

    1. Browser "unload" event:

    You can use the browser’s beforeunload event to notify the server when a user is about to leave the page (e.g., closing the tab or the browser):

    javascript

    window.addEventListener('beforeunload', function (event) {
        // Send an AJAX request to the server to inform about session end
        // Use either fetch or XMLHttpRequest or any other way you use to send AJAX
    });
    

    Remember that there are certain restrictions on what you can do in the beforeunload event due to its synchronous nature, so it’s typically used with beacon requests or with very fast, lightweight requests.
    2. Periodic AJAX "ping":

    Another approach is to periodically send an AJAX "ping" from the client to the server, and if the server doesn’t receive this ping for an extended period of time (like 2x the expected ping interval), it can assume the session has ended or the browser has been closed. This method is also used for keeping sessions alive when needed.
    3. Middleware:

    You can also use middleware to check if a session has expired by comparing the current time against the session’s last activity. This wouldn’t capture the exact moment of browser closing, but it can help you capture session timeouts.
    Handling Multi-Tenant Session Termination:

    For your multi-tenant setup, when notifying the server about session termination, you can send user or tenant-specific information to ensure you’re updating the correct tenant’s database.

    Here’s a simple example combining the beforeunload event and a middleware:

    JavaScript:

    
    window.addEventListener('beforeunload', function (event) {
        fetch('/session-end', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': '{{ csrf_token() }}' // Laravel CSRF token
            },
            body: JSON.stringify({
                // Here you can send any user or tenant-specific info
            })
        });
    });
    

    Laravel Middleware:

    php

    public function handle($request, Closure $next)
    {
        if ($request->path() === 'session-end') {
            // Handle your logic here to mark session end for the user/tenant.
        }
    
        return $next($request);
    }
    

    With these methods, you can roughly gauge the session termination event. Remember, due to the stateless nature of HTTP, you’ll never get 100% accuracy, but these methods should get you very close.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search