#25 Laravel基礎
カスタムArtisanコマンドを作る
カスタムコマンドとは
php artisan make:model や php artisan migrate のように、自分でも独自のコマンドを作れます。定期バッチ処理・データの一括操作・開発ツールなどに使います。
コマンドを生成する
php artisan make:command SendDailyReport
app/Console/Commands/SendDailyReport.php が生成されます。
<?php
// 📁 app/Console/Commands/SendDailyReport.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendDailyReport extends Command
{
// コマンド名と引数の定義
protected $signature = 'report:daily
{date? : 対象日(省略すると昨日)}
{--dry-run : 実際には送信せず確認だけ行う}';
// コマンドの説明(php artisan list で表示される)
protected $description = '日次レポートをメール送信する';
public function handle(): int
{
$date = $this->argument('date')
? now()->parse($this->argument('date'))
: now()->yesterday();
$dryRun = $this->option('dry-run');
$this->info("対象日: {$date->format('Y-m-d')}");
if ($dryRun) {
$this->warn('ドライランモード: 実際には送信しません');
}
// 処理を実装...
$this->info('完了しました');
return Command::SUCCESS; // 0: 成功、1: 失敗
}
}
コマンドを実行する
# 基本の実行
php artisan report:daily
# 引数を渡す
php artisan report:daily 2025-09-30
# オプションを渡す
php artisan report:daily --dry-run
出力スタイル
// 📁 app/Console/Commands/SendDailyReport.php
$this->info('情報メッセージ(青)');
$this->warn('警告メッセージ(黄)');
$this->error('エラーメッセージ(赤)');
$this->line('通常テキスト');
$this->newLine(); // 空行
// テーブル形式で表示
$headers = ['ID', 'タイトル', '公開日'];
$rows = Post::published()->latest()->take(5)->get()
->map(fn ($p) => [$p->id, $p->title, $p->published_at->format('Y-m-d')]);
$this->table($headers, $rows);
// プログレスバー
$bar = $this->output->createProgressBar(100);
$bar->start();
for ($i = 0; $i < 100; $i++) {
// 処理...
$bar->advance();
}
$bar->finish();
$this->newLine();
入力を求める
// テキスト入力
$name = $this->ask('送信先の名前は?');
// 秘密入力(パスワードなど)
$pass = $this->secret('パスワードを入力してください');
// Yes/No確認
if ($this->confirm('本当に送信しますか?', default: false)) {
// 実行
}
// 選択肢
$type = $this->choice('レポートの種類は?', ['日次', '週次', '月次'], default: '日次');
コマンドのスケジュール実行
routes/console.php でコマンドのスケジュールを定義できます(Laravel 11以降)。
// 📁 routes/console.php
use Illuminate\Support\Facades\Schedule;
// 毎日8時に実行
Schedule::command('report:daily')->dailyAt('08:00');
// 毎時実行
Schedule::command('cache:clear')->hourly();
// 毎週月曜の9時
Schedule::command('report:weekly')->weeklyOn(1, '09:00');
// 毎月1日の0時
Schedule::command('report:monthly')->monthlyOn(1, '00:00');
OSのcronを設定する
スケジューラーはcronから1分ごとに起動します。
* * * * * cd /path/to/project && php artisan schedule:run >> /dev/null 2>&1
開発中は php artisan schedule:work で手軽に確認できます。
コマンドの中から他のコマンドを呼ぶ
// 📁 app/Console/Commands/SendDailyReport.php
public function handle(): int
{
// 別のコマンドを実行
$this->call('cache:clear');
$this->call('queue:restart');
return Command::SUCCESS;
}
まとめ
php artisan make:commandでコマンドを生成する$signatureでコマンド名・引数・オプションを定義するhandle()に処理を書き、終了コードを返すroutes/console.phpでスケジュールを設定できる- サーバーのcronから
php artisan schedule:runを毎分起動する
次回はデータのインポートとエクスポートを学びます。