Artisan command for clearing all session data in Laravel - 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.

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/*

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

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:
Create command
php artisan make:command FlushSessions
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();
}
}
Run command
php artisan session:flush
Implementations for other drivers are welcome!

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).

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
Sometimes the most helpful answer is at the end

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.

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.

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

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

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.

Related

Code in Laravel AppServiceProvider halts Composer & build when deploying via DeployHQ

I have the following code in my AppServiceProvider.php file:
<?php
namespace App\Providers;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
if (Schema::hasTable('settings')) {
foreach (Setting::all() as $setting) {
Config::set('settings.'.$setting->key, $setting->value);
}
}
}
}
Which does it's job fine locally, but when I deploy via DeployHQ, it kills the process with the following error:
SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from
information_schema.tables where table_schema = giga and table_name =
settings and table_type = 'BASE TABLE')
Which kinda makes sense, the database doesn't exist on the build server, so the check cannot run as there's nothing to check. Is there a different way to hydrate a settings config with values from a database on boot which doesn't affect the running of php artisan package:discover?
I know it'll probably be asked, but the .env file etc is all set up correctly. This issue is to do with the fact the build server doesn't have the database, but the server the files get piped to does.
Edit:
To give some more context, and perhaps some advice could be given on this, I'm only really using this config value in this code inside a Service class:
public function __construct()
{
$this->domain = config('api.domain');
$this->apiVersion = config('api.version');
$this->bearerToken = config('settings.bearer_token');
$this->clientId = config('api.client_id');
$this->clientSecret = config('api.client_secret');
}
Everything online suggests putting these values into the config, however if it's only being called here would it be okay to retrieve it from the Database directly?

Laravel: how to simplify artisan commands?

I want to simplify the following artisan commands because I have several databases and the migrations for each database are stored in a separate folder.
php artisan make:migration {{name}} --path=/database/migrations/{{folder}}
php artisan migrate:rollback --path=/database/migrations/{{folder}}
to
php artisan make:migration {{name}} {{folder}}
php artisan migrate:rollback {{folder}}
Is this possible and if so how can I implement it?
Since this is not an option in the Laravel commands, a way to implement this yourself is by writing you own commands that call other artisan commands.
To do so, in your terminal write, for example, php artisan make:command MigrateWithPath to create a new command at app/Console/Commands/MigrateWithPath.php. Then, you can call the vanilla implementation Laravel provides at (vendor\laravel\framework\src) \Illuminate\Database\Console\Migrations\MigrateMakeCommand but then in a way that you specify.
Be sure though that the name of your new command needs to be different from the Laravel one, to prevent recursions. Therefore, I have prefixed the name with app: to be like app:make:migration, but feel free to use something else.
Take a look at the following suggestion:
class MigrateWithPath extends BaseCommand
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'app:make:migration {name : The name of the migration}
{folder? : The location where the migration file should be created}';
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$this->call('make:migration', [
'name' => $this->argument('name'),
'--path' => '/database/migrations/' . $this->argument('folder'),
]);
return 0;
}
Then do the same for the rollback command.

Is there a way to disable artisan commands?

Is there a way to disable artisan commands from running at all?
For example, if I wanted to disable php artisan migrate:fresh from running, where would I go to remove/disable the command?
As far as I know, laravel does not have this feature by default. And this is still under laravel ideas.
I also had this problem before and could not find a solution, I am not sure why you want to disable a command. But my case was that in the production environment I never want to run php artisan migrate:fresh. So what I end up with is to override the default command.
For example, in the routes/console.php file:
if ('production' === App::environment()) {
Artisan::command('migrate:fresh', function () {
$this->comment('You are not allowed to do this in production!');
})->describe('Override default command in production.');
}
So, when you are in production, php artisan migrate:fresh will do nothing. You can change the condition based on your requirement, my example is just an idea of how you can override a laravel default command based on some variables in the .env file.
You can do a lot of things here as well, I am not sure why you want to disable the command, so this is the best I can help.
Create a command like the following
<?php
namespace App\Console\Commands\Utils;
use Illuminate\Console\Command;
use Illuminate\Console\Events\CommandStarting;
class PreCommand extends Command
{
protected $signature = 'precommand';
public function handle(CommandStarting $event) {
if (app()->environment(['production'])) {
logger('Trying to fresh database in production');
if ($event->command == 'migrate:fresh') {
$this->output = $event->output;
$this->info('You can not fresh database in the production');
die();
}
}
}
}
And register it in your EventServiceProvider's boot method
<?php
namespace App\Providers;
use App\Console\Commands\Utils\PreCommand;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* Register any events for your application.
*
* #return void
*/
public function boot() {
Event::listen(CommandStarting::class, PreCommand::class);
}
}

Laravel custom artisan command not listed

I have several artisan commands which I wrote.
All of them share common functionality, so instead of extending Command class, I wrote a MyBaseCommand class so all commands extend this one:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SomeCommand extends MyBaseCommand
{
protected $signature = 'mycommands:command1';
protected $description = 'Some description';
:
:
And the base class:
namespace App\Console\Commands;
class MyBaseCommand extends Command
{
:
:
The problem is that from some reason these commands are no longer listed with php artisan.
Any idea how can I force laravel to list these commands as well?
protected $signature = 'mycommands:command1'; //this is your command name
Open app\Console\kernel.php file.
protected $commands = [
\App\Console\Commands\SomeCommand::class,
]
then run
php artisan list
Laravel tries to register the commands for you automatically with:
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
You can find this in the App\Console\Kernel.php
Make sure that your classes have a signature and description property.
It is quite stupid, anyway since it might happen to someone else I leave here the answer:
I wanted to hide the base class, so I had inside it this line:
protected $hidden = true;
Of-course, the value of this variable was propagated to the high-level class, what made the custom commands hidden.
The solution is simply to add to these files this line:
protected $hidden = false;
====================== UPDATE ======================
As #aken-roberts mentions, a better solution is simply making the base class abstract:
namespace App\Console\Commands;
abstract class MyBaseCommand extends Command
{
abstract public function handle();
:
:
In this case artisan doesn't list it, and it cannot be executed.

Laravel 5.5 Queue Dispatch Not Working

Maybe I'm not understanding on Laravel queue works, or maybe it itself is not working, my expected behaviour for Laravel Queue/Dispatch is that if a dispatch is initiated from the Controller, the code dispatched to queue should be executed silently and in the background. The end-user browser should not have to wait for the code to execute.
This is however what happens with my code, the dispatched code to queue leaves the browsers "Spinning..." whilst is executes.
Is this expected behavior? The code:
**Controller:**
public function make_eps_certs($tbl_eps)
{
//dd(Carbon::now()->addMinutes(10))
Log::info('Dispatching maeEPSCert to Queue');
$var_result=makeEPSCerts::dispatch($tbl_eps)->onQueue('eventadmin')
->delay(10);
return redirect()->back();
}
**Job:**
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\partSubs;
use Log;
use Image;
class makeEPSCerts implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
protected $passdata;
public $timeout = 120;
public function __construct($passdata)
{
Log::info('Constructing makeEPSCert');
$this->passdata = $passdata;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
try
{
Log::info('Beginning makeEPSCert');
$tbl_eps=$this->passdata;
.....
Change your LOG_DRIVERin your .env to database and create the needed migration files with php artisan queue:table, after that do a php artisan migrate.
After that you just need to run php artisan queue:work --queue="eventadmin"
and then you will recognize the expected behavior
A more detailed documentation can be found here: https://laravel.com/docs/5.5/queues
You can try again in the following way (I assume that you did instructions in Laravel docs but someday it's not working):
Step 1: drop table 'jobs' in your database.
Step 2: run command 'php artisan migrate' in console to create table 'jobs' again.
Step 3: run command 'php artisan queue:work' in console
Step 4: retry your app
Note that in .env file, you set up:
QUEUE_CONNECTION=database
QUEUE_DRIVER=database
P/s: It works for me!

Resources