0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LaravelのControllerからArtisanコマンドを引数付きで呼び出す

Posted at

ControllerからArtisanコマンドを引数付きで呼び出そうとして、方法が見つかったのでメモ。

引数が一つの場合

コマンド

Console/Commands/TestArg.php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;


class TestArg extends Command
{
    protected $signature
    = 'test:receivearg {your_name}';

    protected $description
    = '引数を1つだけ受け取る';

    public function __construct()
    {
        parent::__construct();
    }

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

        logger($your_name);

        echo 'your name is ' . $your_name;

        return Command::SUCCESS;
    }
}

テスト

Terminal
php artisan test:receivearg "kartis"
// 出力結果:your name is kartis

Controllerから呼び出すとこうなる。

app/Http/Controllers/TestController.php
<?php
use Illuminate\Support\Facades\Artisan;

class TestController extends Controller
{
    public function test()
    {
        Artisan::call('test:receivearg "kartis"');
    }
}

では、この引数が配列だった場合はどうなるか

引数が配列の場合

コマンド

Console/Commands/TestArgArr.php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestArgArr extends Command
{
    use StockTrait;

    protected $signature = 'test:receiveargArr {arr}';

    protected $description = '引数を配列で受け取る';

    public function handle()
    {
        $array = $this->argument('arr');

        logger($array);

        return Command::SUCCESS;
    }
}

コントローラ側

app/Http/Controllers/TestController.php
<?php
use Illuminate\Support\Facades\Artisan;

class TestController extends Controller
{
    public function test()
    {
        $arr = ['kartis',
                'izumi',
                'sigu'];

         Artisan::call('test:receiveargArr', [
             'arr' => $arr
         ]);
    }
}

参考

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?