Summer Sale! All accounts are 50% off this week.

untymage's avatar

database session deletion period?

So when we use database driver for storing sessions all records will permanently save on the database right ? How to tell laravel for example delete all record once a week or another word how to deal with these data?

0 likes
7 replies
bobbybouwmann's avatar
Level 88

You can write a console command that you can run every week through the scheduler. This works like a cronjob on a server.

Documentation commands: https://laravel.com/docs/6.x/artisan#writing-commands

Documentation scheduler: https://laravel.com/docs/6.x/scheduling#defining-schedules

Basically you end up with code like this

DB::table('sessions')
    ->where('last_activity', '<', Carbon::now->subWeek()->timestamp())
    ->delete();
1 like
Snapey's avatar

laravel automatically cleans up stale sessions through a lottery ( it randomly uses a request to piggyback a session cleanup task)

bobbybouwmann's avatar

Aah it also does that for the database

public function gc($lifetime)
{
    $this->getQuery()->where('last_activity', '<=', $this->currentTime() - $lifetime)->delete();
}
James500's avatar

I'm also interested in this, would be there a way to disable the lottery garage collector and call the gc function from a console job so it honours whatever lifetime is set?

James500's avatar

To achieve my query above - you can set the session lottery to [0,100] and then create a console command with this function in:

$session = $this->getLaravel()->make('session');
$lifetime = config('session.lifetime') * 60;
$session->getHandler()->gc($lifetime);

Please or to participate in this conversation.