'Artisan command for clearing all session data in Laravel

What is the artisan command for clearing all session data in Laravel, I'm looking for something like:

$ php artisan session:clear

But apparently it does not exist. How would I clear it from command line?

I tried using

$ php artisan tinker  
...
\Session::flush();

But it flushes session of only one user, I want to flush all sessions for all users. How can I do it?

I tried this:

artisan cache:clear

But it does not clear session, again.



Solution 1:[1]


UPDATE: This question seems to be asked quite often and many people are still actively commenting on it.

In practice, it is a horrible idea to flush sessions using the

php artisan key:generate

It may wreak all kinds of havoc. The best way to do it is to clear whichever system you are using.


The Lazy Programmers guide to flushing all sessions:

php artisan key:generate

Will make all sessions invalid because a new application key is specified

The not so Lazy approach

php artisan make:command FlushSessions

and then insert

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class flushSessions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'session:flush';

    /**
     * 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 mixed
     */
    public function handle()
    {
        DB::table('sessions')->truncate();
    }
}

and then

php artisan session:flush

Solution 2:[2]

If you are using file based sessions, you can use the following linux command to clean the sessions folder out:

rm -f storage/framework/sessions/*

Solution 3:[3]

The problem is that PHP's SessionHandlerInterface does not force session drivers to provide any kind of destroyAll() method. Thus, it has to be implemented manually for each driver.

Taking ideas from different answers, I came up with this solution:

  1. Create command
php artisan make:command FlushSessions 
  1. Create class in app/Console/Commands/FlushSessions.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class FlushSessions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'session:flush';

    /**
     * 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 mixed
     */
    public function handle()
    {
        $driver = config('session.driver');
        $method_name = 'clean' . ucfirst($driver);
        if ( method_exists($this, $method_name) ) {
            try {
                $this->$method_name();
                $this->info('Session data cleaned.');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        } else {
            $this->error("Sorry, I don't know how to clean the sessions of the driver '{$driver}'.");
        }
    }

    protected function cleanFile () {
        $directory = config('session.files');
        $ignoreFiles = ['.gitignore', '.', '..'];

        $files = scandir($directory);

        foreach ( $files as $file ) {
            if( !in_array($file,$ignoreFiles) ) {
                unlink($directory . '/' . $file);
            }
        }
    }

    protected function cleanDatabase () {
        $table = config('session.table');
        DB::table($table)->truncate();
    }
}
  1. Run command
php artisan session:flush

Implementations for other drivers are welcome!

Solution 4:[4]

An easy way to get rid of all sessions is to change the name of the session cookie. This can be easily done by changing the 'cookie' => '...' line in config/session.php file.

This works independently of the session storage you use and also won't touch any other data except the session data (and thus seems preferable over the renewing the app key solution to me, where you would loose any encrypted data stored in the app).

Solution 5:[5]

If you want completely remove session from whatever driver you use. Use this piece of code

\Session::getHandler()->gc(0); // Destroy all sessions which exist more 0 minutes

Tested on "file", "database" drivers.

Solution 6:[6]

This thread is quite much old. But I would like to share my implementation of removing all sesssions for file based driver.

        $directory = 'storage/framework/sessions';
        $ignoreFiles = ['.gitignore', '.', '..'];
        $files = scandir($directory);

        foreach ($files as $file) {
            if(!in_array($file,$ignoreFiles)) unlink($directory . '/' . $file);
        }

Why I have not used linux command 'rm'?

Because PHP is one of the prerequisites for Laravel and Linux is not. Using this Linux command will make our project implementable on Linux environment only. That's why it is good to use PHP in Laravel.

Solution 7:[7]

I know this is an old thread, but what worked for me is just remove the cookies.

In Chrome, go to your develop console, go to the tab "Application". Find "Cookies" in the sidebar and click on the little arrow in front of it. Go to your domainname and click on the icon next to the filter field to clear the cookies for your domain. Refresh page, and all session data is new and the old ones are removed.

Solution 8:[8]

My solution Laravel

// SESSION_DRIVER=file


$files = File::allFiles(storage_path('framework/sessions/'));
foreach($files as $file){
  File::delete(storage_path('framework/sessions/'.$file->getFilename()));
}
//OR

//SESSION_DRIVER=redis

Artisan::call('cache:clear'); // == php artisan cache:clear 

Solution 9:[9]

If you use database session , just delete all data on that table. In my case it is 'sessions' table.

Solution 10:[10]

If you are using the database for session driver, then empty the sessions table. Regenerating the key will cause a lot of problems if you are using single login on many subdomains. Emptying the session table helps reduce the useless data in the session table. You can delete cookies on everyone's browswer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 benjaminhull
Solution 3
Solution 4 miho
Solution 5
Solution 6 Hamees A. Khan
Solution 7 Refilon
Solution 8
Solution 9 Nur Uddin
Solution 10 Etta