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 IlluminateEventsDispatcher class, I found the event dispatcher actually checks for a broadcastWhen method on the event object itself.

See IlluminateEventsDispatcher::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.

Got a project? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.