Phil Kurth

WordPress developer, consultant, nerd

Conditional Broadcasting of Laravel Events

In a recent project using the Laravel framework, I've been getting familiar with WebSockets and came up against a situation where I needed to broadcast an event only when a certain property on a model had changed.

I couldn't find this documented anywhere but, after quick dig into the \Illuminate\Events\Dispatcher class, I found the event dispatcher actually checks for a broadcastWhen method on the event object itself.

See \Illuminate\Events\Dispatcher::shouldBroadcast() – Laravel version in use at the time of writing is 5.7.15.

So, when implementing an event that should only sometimes be broadcast, we can add the following method to the event class:

public function broadcastWhen()
        // …do some checks here…
        return $bool;

Returning FALSE from the above method will stop the broadcast without inhibiting the event itself. This makes it really simple and concise to conditionally broadcast events. Handy.