RSS Amplifier

David Carr's Blog · Feb 5, 2024

How to disable Laravel console commands

0
Sign in to vote or save

dcblog.dev

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 () {
    //
});

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');
});

Running an alternative command:

To run a different command:

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

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'
    ]);
});

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

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

Change the signature to be app:migrate

<?php
namespace 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()
    {
        //
    }
}

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}';

Then inside the handle method collect the path.

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

Subscribe to my newsletter for the latest updates on my books and digital products.

Read the original on dcblog.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.