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

nikocraft's avatar

does laravel remove expired sessions automatically?

I thought that Laravel would delete expired session files, so to test it I set session lifetime to 1 minute. After 1 minute passes I refresh the page and laravel creates new session, however old session is not removed. Is this normal behaviour? If its not normal behavior why is it not removing old session files?

0 likes
4 replies
itcan's avatar

Laravel has a garbage collector which kicks in at random, its called in the session config something like session_lottery I think.

2 likes
TheNodi's avatar

@maxnb

Not all session drivers requires manual cleanup. Something like redis doesn't need it because it automatically deletes expired keys.

If you want to see how it works, take a look at the StartSession middleware, it has a collectGarbage() functions which clears the session based on lottery configurations.

The default configurations are [2, 100]. It means that a random integer is chosen between 1 and 100, if it's lower or equals to 2 the cache will be cleared. (Aka you have a 2% possibility to clear the cache every call).

4 likes
nikocraft's avatar

@TheNodi I put lottery at 100 like this 'lottery' => [100, 100], is that ok to do? now it clears the cache as soon as it expires

1 like
TheNodi's avatar

@maxnb

I don't think that's a good idea, it makes all your requests slower since the garbage collector requires time and resources to delete files/db rows/etc.

You don't need to do that either, even if the old session is found laravel wont use it if it's expired, it'll just return an empty session. Take a look at FileSessionHandler::read($sessionId) for examples, the second if statement checks if the session is still valid. All other handlers have a similar behavior.

1 like

Please or to participate in this conversation.