メインコンテンツへスキップ

はじめに

このチュートリアルでは、revolution/laravel-console-starter を使ってカスタムartisanコマンドを持つLaravelアプリケーションを構築します。 このスターターキットを使うメリット:
  • 迅速なセットアップ — 複雑な設定なしにコンソールアプリ開発をすぐに始められます
  • Laravelエコシステム — タスクスケジューリング・データベース・通知などLaravelの豊富な機能を利用できます
  • Artisanコマンド — Laravelの強力なArtisanシステムで独自コマンドを簡単に作成・管理できます
  • テスト容易性 — Laravelのテストフレームワークでコマンドのテストを記述できます

前提条件

以下のソフトウェアをインストールしてください。

プロジェクトのセットアップ

1

新しいプロジェクトを作成する

ターミナルで以下のコマンドを実行します。
laravel new my-app --using=revolution/laravel-console-starter --no-interaction
my-app ディレクトリが作成され、コンソールアプリの基本構造がセットアップされます。インストール時に以下が自動実行されます。
  • .env.example から .env ファイルの生成
  • php artisan key:generate によるアプリケーションキーの設定
主なディレクトリ構造:
my-app/
├── app/Console/Commands/   # カスタムコマンドを配置
├── .github/workflows/
│   └── cron.yml            # GitHub Actionsスケジュール例
├── config/                 # アプリケーション設定
└── routes/console.php      # コマンド登録
2

環境設定を確認する

デフォルトでは、メール送信はログ出力に設定されています(MAIL_MAILER=log)。実際のメール送信が必要な場合は、.env ファイルでMailgunやPostmark、SESなどのサービスを設定してください。

コンソールコマンドの作成

1

コマンドを生成する

make:command Artisanコマンドで新しいコマンドを作成します。
php artisan make:command YourCommandName --command=your:command
  • YourCommandName — 作成するコマンドのクラス名(例:SendDailyReport
  • your:command — コマンドの呼び出し名(例:report:send-daily
app/Console/Commands/YourCommandName.php が生成されます。
2

コマンドを実装する

生成されたファイルを編集してロジックを実装します。以下はHello Worldコマンドの例です。
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class HelloWorldCommand extends Command
{
    protected $signature = 'hello:world';
    protected $description = 'Displays a hello world message in the log';

    public function handle(): int
    {
        Log::info('Hello, World from Artisan Command!');
        $this->info('Hello, World message has been logged.');
        return Command::SUCCESS;
    }
}
$signature でコマンドの呼び出し名を定義し、handle() メソッドにロジックを記述します。
3

コマンドを実行する

php artisan hello:world
実行後、storage/logs/laravel.log とコンソールにメッセージが出力されます。

GitHub Actionsでのタスクスケジューリング

GitHub Actionsを使えば、サーバーのcronジョブなしにコマンドを定期実行できます。
1

ワークフローファイルを確認する

スターターキットには .github/workflows/cron.yml が事前設定済みで含まれています。
name: cron

on:
  schedule:
    - cron: '0 0 * * *'  # 毎日UTC午前0時

jobs:
  cron:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: shivammathur/setup-php@v2
        with:
          php-version: 8.5
          coverage: none
      - run: composer install --no-dev -q
      - run: cp .env.example .env
      - run: php artisan key:generate
      - run: php artisan inspire
2

コマンドを変更する

php artisan inspire を自分のコマンドに置き換えます。
- name: Run Command
  run: php artisan your:command
複数のコマンドを実行する場合:
- name: Run Commands
  run: |
    php artisan first:command
    php artisan second:command
3

スケジュールを調整する

cron 式を変更して実行頻度を設定します。
cron式実行タイミング
0 0 * * *毎日UTC午前0時
0 */6 * * *6時間ごと
0 0 * * 1毎週月曜日の午前0時
4

機密情報をシークレットで管理する

APIキーやパスワードなどの機密情報はGitHubリポジトリシークレットを使います。GitHubリポジトリの Settings > Secrets and variables > Actions でシークレットを追加し、ワークフローで参照します。
- name: Run Command with Secrets
  run: php artisan your:command
  env:
    API_KEY: ${{ secrets.API_KEY }}
    DB_PASSWORD: ${{ secrets.DATABASE_PASSWORD }}

通知機能

コマンドの実行結果やエラーをメール・Slackなどで通知できます。
1

通知クラスを作成する

php artisan make:notification TaskCompleted
app/Notifications/TaskCompleted.php が生成されます。
2

通知チャネルを設定する

必要に応じて設定ファイルを公開します。
php artisan config:publish mail
php artisan config:publish services
3

コマンドから通知を送信する

<?php

namespace App\Console\Commands;

use App\Notifications\TaskCompleted;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Notification;

class ProcessDataCommand extends Command
{
    protected $signature = 'data:process';
    protected $description = 'データを処理し、完了時に通知を送信';

    public function handle()
    {
        $this->info('データを処理中...');

        // 処理ロジック...

        Notification::route('mail', '[email protected]')
            ->notify(new TaskCompleted('データ処理が正常に完了しました'));

        return Command::SUCCESS;
    }
}
詳細はLaravel通知ドキュメントを参照してください。

実践的なアプリケーション例

例1: ウェブサイト死活監視とSlackアラート

ウェブサイトがオンラインかどうかを確認し、問題が検出された場合にSlackへアラートを送信するコマンドです。
1

Slack通知チャンネルをインストールする

composer require laravel/slack-notification-channel
2

コマンドと通知を作成する

php artisan make:command MonitorWebsites --command=monitor:websites
php artisan make:notification WebsiteDown
3

Slackを設定する

php artisan config:publish services
.env にSlack webhook URLを追加します。
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL
config/services.php を更新します。
'slack' => [
    'webhook_url' => env('SLACK_WEBHOOK_URL'),
],
4

通知を実装する

app/Notifications/WebsiteDown.php を編集します。
<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;

class WebsiteDown extends Notification
{
    public function __construct(
        protected string $website,
        protected string $error,
    ) {}

    public function via($notifiable): array
    {
        return ['slack'];
    }

    public function toSlack($notifiable): SlackMessage
    {
        return (new SlackMessage)
            ->error()
            ->content('ウェブサイトダウンアラート!')
            ->attachment(function ($attachment) {
                $attachment->title($this->website)
                           ->content("エラー: {$this->error}")
                           ->timestamp(now());
            });
    }
}
5

コマンドを実装する

app/Console/Commands/MonitorWebsites.php を編集します。
<?php

namespace App\Console\Commands;

use App\Notifications\WebsiteDown;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;

class MonitorWebsites extends Command
{
    protected $signature = 'monitor:websites {--timeout=10}';
    protected $description = 'ウェブサイトの死活確認とダウン時のSlackアラート送信';

    protected array $websites = [
        'https://example.com',
        'https://yourwebsite.com',
    ];

    public function handle(): int
    {
        $timeout = (int) $this->option('timeout');
        $webhookUrl = config('services.slack.webhook_url');
        $hasErrors = false;

        foreach ($this->websites as $website) {
            try {
                $response = Http::timeout($timeout)->get($website);
                if ($response->successful()) {
                    $this->info("{$website}: オンライン ✓");
                } else {
                    $error = "HTTPステータス: " . $response->status();
                    $this->error("{$website}: ダウン ({$error})");
                    Notification::route('slack', $webhookUrl)
                        ->notify(new WebsiteDown($website, $error));
                    $hasErrors = true;
                }
            } catch (\Exception $e) {
                $this->error("{$website}: エラー ({$e->getMessage()})");
                Log::error("{$website} の確認に失敗", ['error' => $e->getMessage()]);
                Notification::route('slack', $webhookUrl)
                    ->notify(new WebsiteDown($website, $e->getMessage()));
                $hasErrors = true;
            }
        }

        return $hasErrors ? Command::FAILURE : Command::SUCCESS;
    }
}
6

GitHub Actionsでスケジュール設定する

.github/workflows/cron.yml を更新します。
name: Website Monitoring

on:
  schedule:
    - cron: '*/15 * * * *'  # 15分ごとに実行

jobs:
  monitor:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: shivammathur/setup-php@v2
        with:
          php-version: 8.5
      - run: composer install --no-dev -q
      - run: cp .env.example .env
      - run: php artisan key:generate
      - name: Monitor Websites
        run: php artisan monitor:websites
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

例2: 暗号資産ポートフォリオ更新とDiscord通知

CoinGecko APIから暗号資産の価格を取得し、Discordウェブフックで更新を送信するコマンドです。
1

Discord通知チャンネルをインストールする

composer require revolution/laravel-notification-discord-webhook
2

コマンドと通知を作成する

php artisan make:command UpdateCryptoPortfolio --command=crypto:portfolio
php artisan make:notification CryptoPortfolioUpdate
3

Discordを設定する

.env にDiscord webhook URLを追加します。
DISCORD_WEBHOOK=https://discord.com/api/webhooks/YOUR/WEBHOOK
config/services.php を更新します。
'discord' => [
    'webhook' => env('DISCORD_WEBHOOK'),
],
4

コマンドを実装して実行する

詳細な実装についてはGitHubリポジトリのチュートリアルを参照してください。
php artisan crypto:portfolio

例3: ウェブサイトコンテンツのスクレイピングとメール通知

ウェブサイトからコンテンツをスクレイピングし、結果をメールで送信するコマンドです。
1

コマンドと通知を作成する

php artisan make:command WebScraper --command=scrape:website
php artisan make:notification ScrapingCompleted
2

メールを設定する

php artisan config:publish mail
.env ファイルにメール設定を追加します。
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
3

コマンドを実装して実行する

protected $signature = 'scrape:website {--url=https://example.com} {[email protected]}';

public function handle(): int
{
    $url = $this->option('url');
    $email = $this->option('email');

    $response = Http::timeout(30)->get($url);

    // コンテンツを処理して通知を送信...
    Notification::route('mail', $email)
        ->notify(new ScrapingCompleted(true, $url, $title, $content));

    return Command::SUCCESS;
}
php artisan scrape:website [email protected]

次のステップ

これで revolution/laravel-console-starter を使ったLaravelコンソールアプリケーションの基本を学びました。 さらに深く学ぶために:
  • Laravelドキュメントを探索するLaravel公式ドキュメントでコンソールアプリを強化できる機能を確認しましょう
  • テストを実装する — Laravelのテストフレームワークでコマンドのテストを作成し、信頼性を確保しましょう
  • パッケージ開発を検討する — 複数のプロジェクトで同様のコマンドを作成するなら、再利用可能なLaravelパッケージとして公開することを検討してください
  • 最新情報を把握するLaravel News や公式ブログをフォローしてベストプラクティスを常に把握しましょう
最終更新日 2026年5月1日