Laravel Artisan 命令通过 $this->argument() 和 $this->option() 分别读取位置参数与选项参数,需在 $signature 中声明格式(如 {user-id}、{--force}),并在 handle() 中获取并校验。

在 Laravel 命令行(Artisan 命令)中读取外部传入的参数,主要通过 $this->argument() 和 $this->option() 方法实现,分别对应「位置参数」和「选项参数」。
定义参数:在 signature 中声明
在自定义命令类(如 app/Console/Commands/SendEmail.php)的 $signature 属性中声明参数格式:
-
位置参数(必填/可选):用
{name}或{name?}表示,例如send:email {user-id} {template?} -
选项参数(带 -- 前缀):用
{--force}(布尔开关)或{--env=}(带值),例如{--count=10} {--dry-run}
获取参数值:使用 argument() 和 option()
在 handle() 方法中调用:
-
$userId = $this->argument('user-id');→ 获取位置参数user-id -
$template = $this->argument('template');→ 若未传且声明为可选({template?}),返回null -
$count = $this->option('count');→ 返回字符串"10"(即使默认是数字,也需自行转换) -
$isDryRun = $this->option('dry-run');→ 开关型选项,有则为true,否则false
完整示例命令
假设定义签名:php artisan send:email {user-id} {--template=default} {--force}
Laravel Cloud(cloud.laravel.com)。此技能用于处理所有 Laravel Cloud 请求,包括搜索和读取数据。只要任务涉及 Laravel Cloud,即使用此技能。
调用方式:
-
php artisan send:email 123→user-id=123,template="default",force=false -
php artisan send:email 456 --template=welcome --force→ 全部显式指定
在 handle() 中即可安全使用:$this->argument('user-id')、$this->option('template')、$this->option('force')。
验证与默认值建议
推荐在 handle() 开头做基础校验:
- 用
if (!$this->argument('user-id')) { $this->error('user-id 是必需的'); return 1; } - 对数值选项手动转换:
$count = (int) $this->option('count'); - 选项默认值尽量在
$signature中声明(如{--count=5}),而非代码里硬编码

















