5
13

More than 5 years have passed since last update.

LaravelでControllerからartisanを利用する

Posted at

やりたいこと

viewから実行ボタンをクリックしてphp artisan command:hogehogeを実行したい。
引数も渡して利用させたい。

やること

ボタンを置く。

スクリーンショット 2018-10-04 13.16.10.png
こんな感じ。
特にコードはここには書かない。

Controllerの実装

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function hogehoge(Request $request)
    {
        $Ym = $request->year . $request->month;

        Artisan::call('command:hogehoge', ['Ym' => $Ym]);
    }

Artisan::callで呼び出す。
第二引数の配列のkeyに指定した文字列で値を渡す。
stringだけでなくbooleanやint、array型も渡せる。

Command側の実装

$signatureに引数の名前をつける。
"?"をつけることで指定しなくても良くなる。

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:hogehoge {Ym?}';

引数を取得する。
$thisから取得するのでclass内のどこからでも取得できる。

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        dump($this->argument('Ym'));
    }
5
13
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
5
13