Search code examples
laravelcommandlaravel-artisan

Get artisan command signature programmatically


I'm trying to get some info of my custom command in Laravel from my controller, but I don't know which method to get command signature or other info of command. Actually I have a select box with a command list, when choosing an option, my code in back-end will run and return selected command info, then display on textarea.

I have read this question. I also google laravel source but couldn't find where artisan method source placed.

foreach(Artisan::all() as $key=>$command)
{
 echo $command->getDescription(); // show description
 echo $command->getName(); // show name
 echo $command->getSignature(); // error because this method doesn't exist.
}
  1. Is there any method to get command signature or other info?
  2. Where can I find artisan command method source?

Solution

  • From what I can see you are correct, Laravel commands do not offer a getter for signatures. As an alternative you could look into the following workarounds.

    1. You can use the $name as signature.
    protected $name = 'app:do:something';
    

    I'm not sure if this is a common (or best) practice, but it seems to do the trick.

    1. If that doesn't cut it for you, you can implement and extend your own CommandWithSignature (or SignatureAwareTrait) which exposes a getSignature() method.
    public class CommandWithSignature {
        protected $signature;
    
        public function getSignature(): string
        {
            return $this->signature;
        }
    }