Home > Blockchain >  Interact with Artisan command programmatically
Interact with Artisan command programmatically

Time:09-05

First of all, the question is kind of similar to this question, but unfortunately, it does not have an answer.

Consider having an interactive command like the following:

class SayHello extends Command
{
   protected $signature = 'say:hello';

   public handle()
   {
        $name = $this->ask('Your name');
        
        $this->info('Hello, ' . $name . '!');
   }
}

The question is: How to call this command programmatically (in controller, job, tinker, etc.) and answer the question using code (without real-time interaction)?

PS: I already know I can call an artisan command using the Artisan::call() method. I want to know how to handle interaction (questions, choices, etc.)

CodePudding user response:

Artisan::call can be used to execute commands programmatically. Eg:

//use Illuminate\Support\Facades\Artisan;
$name = "John Doe";
Artisan::call('say:hello', [
    'name' => $name,
]);
//OR
Artisan::call('say:hello John');

Call method's first argument is command signature and the second is an array of parameters.

Reference: https://laravel.com/docs/9.x/artisan#programmatically-executing-commands

CodePudding user response:

laravel docs about commands

you can write interactive command console.php, e.g:

`

Artisan::command('hi', function () {
    $name = $this->ask('What is your name?');
    $this->comment('Hi ' . $name);
});

`

  • Related