Search code examples
phplaravelcommand

Laravel Artisan Custom Command - Is there a way to make a help context for options?


Does anyone know if there is a way to create a --help context for any particular command options you would create in the signature of a custom artisan command?

I have created an artisan command that can use a {--task=} option. What I wish to provide for a user is a means of them calling up a help description for the option preceding the --help boolean flag.

I know you can presently accomplish this in artisan if you do something like this;

php artisan make:controller --help

whereby this would then show you some help text about the make:controller command. So, can this be achieved for command options also?


Solution

  • The --help command, when run against a Custom Command, will output something like the following:

    Description:
      // Whatever the value of `protected $description = '...';` is
    
    Usage:
      // Whatever the value of `protected $signature = '...';` is
      // (with additional options truncated)
    
    Options:
      // Additional Options as defined in `protected $signature = '...';`
    
      // All Default options available to each `php artisan ...` command
      -h, --help            Display help for the given command. When no command is given display help for the list command
      -q, --quiet           Do not output any message
      -V, --version         Display this application version
          --ansi|--no-ansi  Force (or disable --no-ansi) ANSI output
      -n, --no-interaction  Do not ask any interactive question
          --env[=ENV]       The environment the command should run under
      -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
    

    If you define your command as such:

    <?php
    
    namespace App\Console\Commands;
    
    class MyCutomCommand extends Command {
      protected $signature = 'my-custom-command {--task : Valid Options: A, B, C}';
      protected $description = 'This is a Custom Command';
    
      public function handle() {
        // Command Logic...
      }
    }
    

    When you then run php artisan my-custom-command --help, you'll see the above, or more specifically:

    enter image description here

    In your case, if your valid options is dynamic (or simply too long), you can adjust your code as such:

    private $validOptions = ['Long', 'List', 'of', 'Options'];
    
    public function __construct() {
      // $validOptions = DB::table('valid_options')->pluck('name');, etc etc
      
      $this->signature = 'my-custom-command {--task : Valid Options: ' . implode(', ', $this->validOptions) . '}';
    
      parent::__construct();
    }
    

    Documentation:

    https://laravel.com/docs/10.x/artisan#input-descriptions