LoginSignup
1
1

Laravel 11でコマンドラインアプリケーションを作成【コンソールアプリ】

Last updated at Posted at 2024-02-22

Laravel 11のインストール

Laravel 11はPHP8.2以上が必要です

composer create-project laravel/laravel:^11.0 example-app
cd example-app

コマンドラインアプリケーションを作成

routes/console.php
<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();

$this->comment();でコンソールに色を付けてくれます。->hourly();で毎時に実行されます!

実行

$ php artisan inspire

  “ Always remember that you are absolutely unique. Just like everyone else. ”
  — Margaret Mead

コマンドラインアプリケーションを作成

php artisan make:command SendEmails

編集

app/Console/Commands/SendEmails.php
<?php

namespace App\Console\Commands;

use Illuminate\Foundation\Inspiring;
use Illuminate\Console\Command;

class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send-emails';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->comment(Inspiring::quote());
    }
}

実行

$ php artisan app:send-emails

  “ Simplicity is the consequence of refined emotions. ”
  — Jean D'Alembert

スケジュール

Laravel 10以上なら1分未満の間隔を指定できます!便利!

routes/console.php
<?php

use Illuminate\Support\Facades\Schedule;
 
Schedule::command('app:send-emails')->everySecond();

cronをインストール

sudo apt install -y cron
sudo service cron start
service cron status
crontab -e

/path-to-your-projectphpのパスは適宜書き換えること

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
1
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
1
1