0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LaravelAdvent Calendar 2024

Day 16

laravel 画面からのトリガーで自作のcommandをキューを使って非同期実行してみる

Last updated at Posted at 2024-12-24

概要

laravelにて画面上からのボタンクリックトリガーで自作のcommandを実行する方法をまとめる。

前提

下記の内容が完了していること。

DBにjobsテーブルがあること

方法

  1. .envのQUEUE_CONNECTIONをdatabaseに設定(configのキャッシュクリア$ php artisan config:clearを実行した方が良い)

  2. 下記コマンドを実行してジョブを作成

    php artisan make:job EchoHelloWorldCommandJob
    
  3. 作成されたジョブapp/Jobs/EchoHelloWorldCommandJob.phpを開き下記のように記載

    app/Jobs/EchoHelloWorldCommandJob.php
    <?php
    
    namespace App\Jobs;
    
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Queue\Queueable;
    use Illuminate\Support\Facades\Artisan;
    
    class EchoHelloWorldCommandJob implements ShouldQueue
    {
        use Queueable;
    
        /**
         * 実行するコマンド名
         *
         * @var string
         */
        protected $command;
    
        /**
         * Create a new job instance.
         */
        public function __construct()
        {
            $this->command = 'app:echo-hello-world-command';
        }
    
        /**
         * Execute the job.
         */
        public function handle(): void
        {
            Artisan::call($this->command);
        }
    }
    
    
  4. ワーカーの起動

    php artisan queue:work
    
  5. トリガーとなる処理の後に下記の1行を追加

    use App\Jobs\EchoHelloWorldCommandJob;
    
    EchoHelloWorldCommandJob::dispatch();
    
  6. 後は処理を実行するだけ

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?