Skip to content

Instantly share code, notes, and snippets.

@ArielMejiaDev
Forked from JuanDMeGon/Kernel.php
Created April 29, 2020 19:38
Show Gist options
  • Save ArielMejiaDev/51240c836442d297db84d29790e4d0f7 to your computer and use it in GitHub Desktop.
Save ArielMejiaDev/51240c836442d297db84d29790e4d0f7 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment