1
0

DatabaseSessionGarbageCollector.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. class DatabaseSessionGarbageCollector extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'gc:sessions';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'Database sessions garbage collector';
  19. /**
  20. * Create a new command instance.
  21. *
  22. * @return void
  23. */
  24. public function __construct()
  25. {
  26. parent::__construct();
  27. }
  28. /**
  29. * Execute the console command.
  30. *
  31. * @return int
  32. */
  33. public function handle()
  34. {
  35. if(config('session.driver') !== 'database') {
  36. return Command::SUCCESS;
  37. }
  38. DB::transaction(function() {
  39. DB::table('sessions')->whereNull('user_id')->delete();
  40. });
  41. DB::transaction(function() {
  42. $ts = now()->subMonths(3)->timestamp;
  43. DB::table('sessions')->where('last_activity', '<', $ts)->delete();
  44. });
  45. return Command::SUCCESS;
  46. }
  47. }