shouldQueue method may be added to a listener to determine whether the listener should be queued. If the shouldQueue method returns false, the listener will not be executed (not be sent to queue)

<?php

namespace App\Listeners;

use App\Events\OrderCreated;
use Illuminate\Contracts\Queue\ShouldQueue;

class RewardGiftCard implements ShouldQueue
{
    /**
     * Reward a gift card to the customer.
     *
     * @param  \App\Events\OrderCreated  $event
     * @return void
     */
    public function handle(OrderCreated $event)
    {
        //
    }

    /**
     * Determine whether the listener should be queued.
     *
     * @param  \App\Events\OrderCreated  $event
     * @return bool
     */
    public function shouldQueue(OrderCreated $event)
    {
        return $event->order->subtotal >= 5000;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Refs:

  • https://laravel.com/docs/master/events#conditionally-queueing-listeners
  • https://github.com/laravel/framework/blob/9.x/src/Illuminate/Events/Dispatcher.php#L562

Powered by VuePress
Copyright 2010-2024 Thai Nguyen Hung all rights reserved.