How to throttle broadcast events in laravel?

by darrion.kuhn , in category: PHP Frameworks , 7 months ago

How to throttle broadcast events in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 7 months ago

@darrion.kuhn 

In Laravel, you can throttle broadcast events using the throttle method. This method allows you to limit the frequency at which a specific event is broadcasted within a specified time frame.


Here's an example of how you can throttle a broadcast event in Laravel:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcastNow;

class OrderShipped implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

    public function __construct($order)
    {
        $this->order = $order;
    }

    public function broadcastOn()
    {
        return new Channel('orders');
    }

    public function broadcastWith()
    {
        return [
            'order_id' => $this->order->id,
            'status' => $this->order->status,
        ];
    }

    public function broadcastWhen()
    {
        return $this->order->status === 'shipped';
    }

    public function broadcastWithDelay()
    {
        return now()->addSeconds(10);
    }

    public function broadcastThrottle()
    {
        return now()->addSeconds(30);
    }
}


In the OrderShipped event class, you can use the broadcastThrottle method to set a throttle time for the event. In this example, the event will be throttled for 30 seconds, meaning it will only be broadcasted once every 30 seconds.


By using the broadcastThrottle method, you can control the frequency of broadcasted events to prevent overloading your server with too many broadcasts at once.