Search code examples
laravel

Listener Execution Priority in Laravel 11


I have created two listeners (one for sending an email and the other for processing a video) without writing any code to manually link them. It seems that in Laravel 11, the connection between the event and the listeners happens automatically.

Both listeners are working fine, but the problem is that the second listener (video processing) runs before the first one (email sending).

How can I ensure that the listeners execute in the correct order?

How can I control the execution order of these listeners in Laravel 11?


Solution

  • You could have 2 separate queues to control execution priority for this. In your config/queue.php, you can create a high and low priority queues:

    'high' => [
       'driver' => 'database',
       'connection' => env('DB_QUEUE_CONNECTION'),
       'table' => env('DB_QUEUE_TABLE', 'jobs'),
       'queue' => env('DB_QUEUE', 'default'),
       'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
       'after_commit' => false,
    ],
    
    'low' => [
       'driver' => 'database',
       'connection' => env('DB_QUEUE_CONNECTION'),
       'table' => env('DB_QUEUE_TABLE', 'jobs'),
       'queue' => env('DB_QUEUE', 'default'),
       'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
       'after_commit' => false,
    ],
    

    After that, when firing events, you can define on which queue they will be dispatched, using the onQueue() method:

    VideoEvent::dispatch()->onQueue('high');
    EmailEvent::dispatch()->onQueue('low');
    

    All you have to do at the end, is to run your queue like this:

    php artisan queue:work --queue=high,low
    

    This will ensure that all of the high queue jobs are processed before continuing to any jobs on the low queue.

    Read more on official docs: https://laravel.com/docs/11.x/queues#queue-priorities