Search code examples
laravellaravel-6laravel-artisan

Retrieve value of optional Artisan command option


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.


Solution

  • 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!