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

ronnyandre's avatar

Alert user of session timeout

In my app I want to alert the user that his or her session is about to timeout. They should be presented an alert box that allows them to refresh/update the session so that they won't be timed out.

The best would be to do this through AJAX, but when using API routes I don't have the same session data as in the normal web routes.

My test code in the web.php file works:

    $session_id = $request->cookies->get('app_session');
    $last_activity = DB::table('sessions')
        ->select('last_activity')
        ->where('id', $session_id )
        ->first()
        ->last_activity;
    
    $expires = $last_activity + config('session.lifetime') * 60;

    $expiresCarbon = Carbon::createFromTimestamp( $expires );
    $lastActivityCarbon = Carbon::createFromTimestamp( $last_activity );

    return Carbon::now()->diff( $expiresCarbon )->format('%H:%I:%S');

This returns your time left of the session, but putting this code in api.php route file doesn't work.

Any ideas or tips?

0 likes
1 reply
Braunson's avatar

API routes (routes/api.php) are stateless which is why it doesn't work. You can create a new middleware group called something like apI_local and enable the session middleware on it,

Please or to participate in this conversation.