Laravel Customized Session.Lifetime at User Level

How does an HTTP session exactly work and in what cases does it expire (in Laravel)?

As you can see, session is dependent on the driver you choose, and at the same time you can select the timeout as well in config\session.php.

In case of Cookie, the session will expire in two cases:

  1. Once the cookie has expired/deleted.
  2. Or (current_time - cookie_creation_time) > session_timeout set in the session.php.

In all drivers, one thing is common: whenever you access the website, and a request is made to the server, it will add the last access time and calculate the session timeout from there.

When the user navigates from the browser and the cookie is still there and it hasn't expired, the user will be identified and session will remain the same.

I hope it's clearer... If not, let me know. I will share some examples.

Laravel session expire time for each session

You can change the session lifetime, application wide by changing the lifetime value on config/session.php:

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 4320,
'expire_on_close' => false,

Now, if you want to control the session lifetime per user, you need to set this value before logging in the user.

  1. Try if user exists in database
  2. If yes, and he is user who needs longer session lifetime, run config(['session.lifetime' => $newLifetime]);
  3. Log user in
  4. Enjoy longer session lifetime for current user

— Source

You have to make the above changes in LoginController.



Related Topics



Leave a reply



Submit