DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

How to disable Laravel console commands

Suppose you find yourself in a situation where you need to disable or intercept a console command in Laravel. This tutorial will primarily focus on how to intercept the php artisan migrate command. We'll delve into the command method app/Console/Kernel.php and explore how to prevent the migrate command from executing any actions.

Inside the command method of app/Console/Kernel.php

In Laravel 11 use routes/console.php

Intercept command

You can intercept php artisan migrate and, instead, catch it and use a closure.

Artisan::command('migrate', function () { //});
Enter fullscreen mode Exit fullscreen mode

This would essentially stop the migrate command from doing anything.

You could then print a message out:

Artisan::command('migrate', function () { $this->info('Command NOT AVAILABLE. Use this: php artisan app:migrate');});
Enter fullscreen mode Exit fullscreen mode

Running an alternative command:

To run a different command:

Artisan::command('migrate', function () { $this->call('app:migrate');});
Enter fullscreen mode Exit fullscreen mode

In this case, a new command called app:migrate would be executed.

Run command with a --path option:

Artisan::command('migrate', function () { $this->call('app:migrate', ['--path' => 'database/migrations']);});
Enter fullscreen mode Exit fullscreen mode

Now when running php artisan migrate you will get an error:

The "--path" option does not exist.

The reason for this is the custom command does not have a path option. Lets create the command and add the option.

Create a command:

php artisan make:command AppMigrate
Enter fullscreen mode Exit fullscreen mode

This creates a class called AppMigrate.php inside app/Console/Commands

Change the signature to be app:migrate

<?phpnamespace App\Console\Commands;use Illuminate\Console\Command;class AppMigrate extends Command{ / *** The name and signature of the console command. * * @var string */ protected $signature = 'app:migrate'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Execute the console command. */ public function handle() { // }}
Enter fullscreen mode Exit fullscreen mode

Now for this command to accept a path change the signature to accept a path.

protected $signature = 'app:migrate {--path= : The path to the migrations}';
Enter fullscreen mode Exit fullscreen mode

Then inside the handle method collect the path.

public function handle(){ $path = $this->option('path') ?? 'database/other-path/migrations'; //rest of the logic ...}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)