Skip to content

Instantly share code, notes, and snippets.

@JuanDMeGon
Last active November 28, 2023 15:13
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JuanDMeGon/f086e5b6e4f71ae1a1b5e66ff08814e9 to your computer and use it in GitHub Desktop.
Save JuanDMeGon/f086e5b6e4f71ae1a1b5e66ff08814e9 to your computer and use it in GitHub Desktop.
A small Laravel command to collect the sessions garbage if applicable to the current session driver
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
//...
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//...
$schedule->command('session:gc')
->hourly();
//...
}
//...
}
<?php
//...
return [
//...
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [0, 1],
//...
];
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SessionGarbageCollector extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'session:gc';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clears the sessions garbage if applicable to the current driver';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
session()->getHandler()->gc($this->getSessionLifetimeInSeconds());
}
/**
* Get the session lifetime in seconds.
*
* @return int
*/
protected function getSessionLifetimeInSeconds()
{
return (config('session.lifetime', null)) * 60;
}
}
@JuanDMeGon
Copy link
Author

Be sure to schedule this command to be executed at least every hour:

$schedule->command('session:gc')
            ->hourly();

@JuanDMeGon
Copy link
Author

Be sure to "disable" the session lottery to avoid the random garbage collection of session:

//In config/session.php
'lottery' => [0, 1],

@JuanDMeGon
Copy link
Author

Here is the article that shows this session problem in detail, to understand the usage of this gist: https://ma.ttias.be/disable-http-sessions-in-laravel-to-speed-up-your-api/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment