はじめに
Laravelではphp artisan make:commandで独自のコマンドを作成できます。バッチ処理やデータ移行などに便利です。
コマンドの作成
php artisan make:command SyncDataCommand
これでapp/Console/Commands/SyncDataCommand.phpが生成されます。
基本構造
class SyncDataCommand extends Command
{
// コマンド名と引数・オプションの定義
protected $signature = 'app:sync-data
{target : 対象を指定}
{--force : 強制実行}';
protected $description = 'データを同期するコマンド';
public function handle(): int
{
$target = $this->argument('target');
$force = $this->option('force');
$this->info("処理開始: {$target}");
// 処理...
$this->info('完了');
return 0; // 成功
}
}
便利な出力メソッド
$this->info('情報メッセージ'); // 緑
$this->warn('警告メッセージ'); // 黄
$this->error('エラーメッセージ'); // 赤
$this->line('通常メッセージ');
$this->newLine(); // 空行
実行方法
# 基本
php artisan app:sync-data users
# オプション付き
php artisan app:sync-data users --force
まとめ
Artisanコマンドを活用すると、定期バッチやデータ処理を簡単に実装できます。