I have a command with this signature

order:check {--order}

执行以下命令:

php artisan order:check --order 7

由于某种原因导致了这个例外

  [RuntimeException]                                 
  Too many arguments, expected arguments "command".  

Why? I want that this command can either be executed as php artisan order:check or with an optional order id php artisan order:check --order X

推荐答案

The {--order} option (without an = sign) declares a switch option, which takes no arguments. If the switch option is present, its value equals true, and, when absent, false (--help is like a switch—no argument needed).

When we provide an argument on the command line for this option, the console framework cannot match the input to an option with an argument, so it throws the error as shown in the question.

要允许选项接受参数,请将命令的$signature更改为:

protected $signature = 'order:check {--order=}'

Note the addition of the equal sign after --order. This tells the framework that the --order option requires an argument—the command will throw an exception if the user doesn't provide one.

如果我们希望命令接受选项with or without作为参数,我们可以使用类似的语法来提供默认值:

protected $signature = 'order:check {--order=7}'

...but this doesn't seem useful for this particular case.

设置好后,我们可以调用命令,传递一个参数--order.该框架支持两种格式:

$ php artisan order:check --order=7 
$ php artisan order:check --order 7 

...and then use the value of order in our command:

$orderNumber = $this->option('order');  // 7

Laravel相关问答推荐

前端和管理员分开时未加载laravel 9中间件

1 子编译中的警告(使用'stats.children:true'和'--stats-children'了解更多详细信息)

Laravel Debugbar 中的 Laravel api routes路由

当使用Laravel eloquent查询100000条数据时速度很慢

如何保存/重定向 Laravel Artisan 命令的输出?

验证规则 required_if 与其他条件(Laravel 5.4)

Laravel 价格验证只接受正数而不是 0

Laravel 5.1 如何在Blade 文件上使用 {{ old('') }} 助手进行无线电输入

Laravel 5 - ErrorException 无法打开流:权限被拒绝

在 VSCode 上调试 Laravel 应用程序

Laravel 中的合同和 PHP 中的接口有什么区别?

如何在新安装时指定 Lumen(或 Laravel)版本?

如何使用外部图像生成 html div 的 screenshot截图?

Web 服务器如何处理请求?

当表中不存在列时如何将 paginate() 与 having() 子句一起使用

Laravel 中的单会话登录

Laravel 邮件密件抄送

Laravel 中的 isDirty() 是什么意思?

Distinct values with pluck

Laravel 5 Auth注销不起作用