【问题标题】:Retrieve value of optional Artisan command option检索可选 Artisan 命令选项的值
【发布时间】:2022-10-07 22:51:38
【问题描述】:
Laravel 版本:6.20.44
我有以下带有可选日期参数的命令:
protected $signature = 'do-my-thing {--date?=}';
我查看是否已设置选项:
$dateToDoThing = $this->option('date');
如果它设置,我想使用该值:
if ($dateToDoThing) {
// ... validate, create date from string format
$now = Carbon::createFromFormat($dateFormat, $dateToDoThing);
} else {
$now = Carbon::now();
}
因此,当我运行命令时,不添加日期,我收到以下错误:
“日期”选项不存在。
我改为尝试使用参数,但现在我得到:
“日期”参数不存在。
我认为通过在方法签名中的选项之后添加? 意味着它是可选的?我觉得我在这里遗漏了一些非常明显的东西,如果有人能指出我的方向,我将不胜感激。
【问题讨论】:
标签:
laravel
laravel-6
laravel-artisan
【解决方案1】:
您是否尝试过使用可选参数而不是选项?
这对我有用:
<?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;
}
}
请注意,当您期望输入而不是选项时,您应该使用$this->argument();