How long does data last in session in laravel?

2020-07-17 15:07发布

问题:

Recently, I have noticed a very disturbing situation with my laravel 5 app which I can't seem to figure out. During login, I set the user_type variable in session like so

Session::put('is_supervisor', $user->is_supervisor);

In my config/session.php file, I have the following configuration:

'lifetime' => 120,
'expire_on_close' => false,

I have also implemented the remember me functionality.

I logged in as a supervisor user with remember me checked. After a few hours, I close the browser without logging out and launch again which logged into the user profile as expected since expire_on_close was set to false and remember me was checked. But, I notice that the is_supervisor variable didn't exist any more in session so I had to logout and login again to have the variable back in session. What could be the problem? I am using file as my session driver.

回答1:

You need to understand what happened: You've set the lifetime of the sessions to 120 minutes, which means after 120 minutes the session is flushed.

The remember_me feature is using cookies. If there is no user session Laravel checks the cookies and recreates the session if the session cookie is still valid.

My question for you is: Why do you store this data in a session? If you want to check if a user is a supervisor just do if ($user->is_supervisor).

If there is some db query that happens inside the is_supervisor function then use some caching mechanism.