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
]);
}
}
参考