【问题标题】:Pass optional arrgument Laravel 5.8, cron job传递可选参数 Laravel 5.8,cron 作业
【发布时间】:2019-07-04 23:31:20
【问题描述】:
protected $signature = 'do_command {import=false}';
public function handle(){
    $import= $this->argument('import');

    if($import){
        // do something else
    }

}

我在控制器中使用它,而不仅仅是:

    $command = 'do_command';
    $option = null;
    if($import){
        $option = 'import';
    }
    Artisan::call($command, [$option]);

问题是,没关系,如果控制器中的$importtrue/false,if 语句总是被执行并且$this->argument('import')handle 方法中总是为真,即使我调用Artisan::call($command)没有第二个论点。

【问题讨论】:

  • 默认值是(字符串)“false”,实际上不是 false。这意味着它在你的 if 语句中是正确的。我认为您还应该将选项传递为 ['import' => true] 而不是 ['import']

标签: php laravel laravel-5 cron


【解决方案1】:

您将import 的默认值定义为false,即string。因此,您命令中的 if 条件将始终为 true

if ($import) {
    // 
}

您可以做的是更改签名以将导入选项设为optional

protected $signature = 'command:name {import?}';

然后在你的控制器中:

Artisan::call($command, [
    'import' => $import,
]);

【讨论】:

    【解决方案2】:

    首先将选项定义为参数。

    class GenerateApiToken extends Command
    {
        protected $signature = "apitoken:generate
        {--id= : A description of the option}
        {--value= : A description of the option}
        ";
    
        public function handle()
        {
            $id = $this->option('id');
            $value = $this->option('value');
        ...
    

    然后使用$this->option()抓取它们

    在应用程序的调用中使用它们:

    Artisan::call('apitoken:generate', ['id' => $id]);
    

    编辑:我认为您的不起作用的原因是因为您在::call() 的第二个参数中传递命令的数组不是具有代表选项的键名的关联数组。

    【讨论】:

    • import argument doesn't exists。我尝试过使用-- - --import argument doesn't eexists 或不使用--
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2020-01-23
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多