5

From Laravel documentation you can create your own artisan commands and add parameters with descriptions

{--param= : description}

For example if user not enter a required parameter I want to show this parameter and it description like is defined in $signature property.

How can I do this?

gvd
  • 1,482
  • 6
  • 32
  • 58

2 Answers2

8

You can display all options available for a command with calling it with -h or --help option:

php artisan yourcommand -h

To add description to parameters use this syntax:

protected $signature = 'yourcommand {someargument : Description of option}';

If you want to do that programmatically, create a public method in the command class:

public function help()
{
    // Display all arguments with descriptions.
    foreach($this->getDefinition()->getArguments() as $name => $description) {
        echo $name . ' - ' . $description->getDescription();
    };

    // Display all options with descriptions.
    foreach($this->getDefinition()->getOptions() as $name => $description) {
        echo $name . ' - ' . $description->getDescription();
    };
}

Then call it from your code:

app('\App\Console\Commands\YourCommand')->help();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • I know this typed in the terminal, but that I'm looking for is do this from code not from terminal. Is it possible to do it? – gvd Jan 14 '18 at 17:23
  • It works to get all descriptions, but how to get names, too. In the code $name is not defined. – gvd Jan 14 '18 at 18:50
  • 1
    @omixam I've fixed that, so `$name` should work now. But you also can use `->getName()` method as you use `->getDescription()`. – Alexey Mezenin Jan 14 '18 at 18:52
  • There is a cleaner way to programatically show the help text; I've posted it as a separate answer. – Max Dec 01 '21 at 10:04
1

If you want to display the help text programatatically, you can use the base Symfony methods to achieve this easily from inside your Laravel command:

$help = new \Symfony\Component\Console\Command\HelpCommand\HelpCommand();
$help->setCommand($this);
$help->run($this->input, $this->output);

See this SO answer.

Max
  • 374
  • 1
  • 4
  • 10