Ⅰ. はじめに
タイトルの通り「Laravelでコマンドを実行する方法」です。
Ⅱ. 手順
1. プロジェクトを新規作成する
composer create-project laravel/laravel TestProject --prefer-dist
2. コマンドを作成する
php artisan make:command SayHello
3. サンプルプログラムを書く
TestProject/app/Console/Commands/SayHello.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class SayHello extends Command { protected $signature = 'say:hello {name}'; protected $description = 'Say hello to user'; public function __construct() { parent::__construct(); } public function handle() { $name = $this->argument('name'); // Log::debug("Hello {$name}"); echo("Hello {$name}"); return 0; } }
実行結果
$ php artisan say:hello tanaka Hello tanaka
その他
タスクスケジュール実行する方法
FAQ
Q. 以下のようなエラーが表示されます
The stream or file "/var/www/laravel/storage/logs/laravel-2022-01-01.log" could not be opened: failed to open stream: Permission denied
A. cronの実行権限を適切に設定する必要があります
例. www-dataとして実行する
* * * * * cd /var/www/html/MyWebSite/ && su -c "php artisan schedule:run >> /dev/null 2>&1" -s /bin/sh www-data