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,
Nov 22, 2018
1
Level 2
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?
Please or to participate in this conversation.