PHIL KURTH

Email

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.

One last thing…

If you liked this article, I'd be incredibly grateful if you tweeted about it.

Also, I don't send emails often but when I do, I try to fill them full of useful goodies. If you like code snippets & dev tips, join my mailing list. There's no catch but I'll probably want to tell you about any new plugins & tools I build.