skip to Main Content

Laravel version: 6.20.44

I have the following command with an optional date param:

protected $signature = 'do-my-thing {--date?=}';

I look to see if the option has been set:

$dateToDoThing = $this->option('date');

and if it set, I want to use the value:


if ($dateToDoThing) {
    // ... validate, create date from string format
    $now = Carbon::createFromFormat($dateFormat, $dateToDoThing);
} else {
    $now = Carbon::now();
}

So when I run the command, without adding a date, I get the following error:

The "date" option does not exist.

I have instead tried using argument, but now I get:

The "date" argument does not exist.

I thought by adding the ? after the option in the method signature meant it was optional? I feel like I’m missing something quite obvious here, if anyone can point me in the direction I’d be most grateful.

2

Answers


  1. Chosen as BEST ANSWER

    I managed to resolve the problem with an option, rather than an argument, by doing the following:

    In the signature:

    protected $signature = 'do-my-thing {--date=}';

    In my method:

    if (!$this->option('date')) {
        return CarbonImmutable::now('UTC');
    }
    

    I didn't need to add the question mark in the signature, because it is an 'option' it is always optional. Hope that helps someone else out there!


  2. Have you tried with optional argument instead of an option ?

    This works for me:

    <?php
    
    namespace AppConsoleCommands;
    
    use IlluminateConsoleCommand;
    
    class TestCommand extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'test:command {date?}';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Command description';
    
        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        /**
         * Execute the console command.
         *
         * @return int
         */
        public function handle()
        {
            $date = $this->argument('date');
    
            $this->info($date);
    
            return 0;
        }
    }
    

    Note that when you are expecting an input and not an option you should use $this->argument();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search