LoginSignup
30
32

More than 5 years have passed since last update.

Artisan Console の引数・オプション値を取得したい時

Posted at
php artisan hoge hanako --age=20

こういう hanako という引数や --age=20 といったオプションの値を取得するにはどうするの、という話。

公式ドキュメントの場所

指定方法 : Defining Input Expectations
https://laravel.com/docs/5.6/artisan#defining-input-expectations

値の取得方法 : Command I/O
https://laravel.com/docs/5.6/artisan#command-io

引数 Arguments

コマンドでの指定方法

引数を指定する時は {user} のように {} で囲むだけ。

protected $signature = 'email:send {user}';
protected $signature = 'email:send {user?}'; //null許容
protected $signature = 'email:send{user=henohenomoheji}'; //デフォルト指定

実際に実行するコマンドは

php artisan email:send hanako

引数の取得

引数で落ちてくる hanako を取得するには $this->argument('user') とする。

public function handle()
{
    $user = $this->argument('user');
}

オプション Options

コマンドでの指定方法

オプションに値を渡す時は {--age=} というように -- をprefixして = に値を渡す。

protected $signature = 'email:send {user} {--age=}';
protected $signature = 'email:send {user} {--age=18}' //デフォルト指定;
protected $signature = 'email:send {user} {--Q|age=}'; //ショートカット記法

実際に実行するコマンドは

php artisan email:send hanako --age=20

あくまでオプションなので、コマンド実行時に --age=20 がなくてももちろん動く。

オプション値の取得

オプション値の 20 を取得するには $this->option('age') とする。

public function handle()
{
    $age = $this->option('age');
}
30
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
32