Laravel

Controllerからartisanコマンドを実行する方法

Laravelで作成したアプリケーションで、cronを使ってDBの更新を定期的に行っているのですが、状況により手動で更新できる機能を実行してほしいと依頼を受けました。

更新は、Kernel.phpにこのように記載

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\UpdateCommand::class
    ];
 
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
 
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('command:update')->dailyAt('4:15');
    
    }

Commands/UpdateCommand.phpに

01
02
03
04
05
06
07
08
09
10
11
12
13
class UpdateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:update';
 
    public function handle()
    {
    /* 処理内容 */
    }

のように作成。

これを、controllerから呼び出す方法です。

1
2
3
4
public function index(){
 
      Artisan::call('command:update');
}

これでOK.

Artisanはnamespace App\Http\Controllersの中に含まれているようです。