In this episode, we dive into real-time broadcasting of new messages in our chat app. The main goal is to make sure that when someone sends a message in a chat room, it instantly appears for everyone else in that room without requiring a page refresh.
We start by making sure our real-time WebSocket server is running and then move on to creating a Laravel event called MessageCreated
. We talk about how events work in Laravel and why using ShouldBroadcastNow
ensures the message gets sent out immediately, without being queued. Then, we set up broadcast channels in such a way that each chat room gets its own channel—making sure messages only go to users in the right room.
Next, we integrate broadcasting into the message creation process, making sure to only broadcast to other users, not to yourself (since your own message is already handled locally). We also look at the channel authorization, set it to private
(preparing for presence channels down the road), and show how to customize the broadcasted payload. Instead of blasting all the message or room data over the wire, we trim this down to just the essentials (like the message ID), keeping everything nice and lightweight.
Finally, we connect everything on the frontend with Livewire and Laravel Echo, so messages received via broadcast push straight into the Livewire component—no JavaScript needed! At the end, we see it all working: sending a message in one browser instantly appears in another. Next up, we'll tackle auto-scrolling, but for now, we've got real-time message updates working smoothly.