Skip to content

Instantly share code, notes, and snippets.

@mavisland
Created September 4, 2025 07:55
Show Gist options
  • Select an option

  • Save mavisland/6c966e184d873fc4b7d657f559a0be3a to your computer and use it in GitHub Desktop.

Select an option

Save mavisland/6c966e184d873fc4b7d657f559a0be3a to your computer and use it in GitHub Desktop.
Laravel Flush All Sessions Command
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\File;
/*
*I've only include File & DB drivers for now but adding others like Redis, Memcache etc will be easy enough too.
Usage: $ php artisan session:flush will flush the current configured session drive (see your .env) $php artisan session:flush --driver=all will flush all session drivers. This is useful if you've switched driver recently.
*/
class FlushSessions extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'session:flush {--driver=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Flush all user sessions';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$driver = $this->option('driver') ?: config('session.driver');
switch ($driver)
{
case 'database': $this->flushDB();
break;
case 'file': $this->flushFile();
break;
case 'all': $this->flushDB();
$this->flushFile();
break;
}
}
private function flushDB()
{
$table = config('session.table');
if (Schema::hasTable($table)) {
DB::table($table)->truncate();
error_log($table.' was truncated');
} else {
error_log($table.' table does not exist');
}
return;
}
private function flushFile()
{
$path = config('session.files');
if (File::exists($path)) {
$files = File::allFiles($path);
File::delete($files);
error_log( count($files).' sessions flushed');
} else {
error_log('check your session path exists');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment