In this episode, we dig into how to broadcast events on private channels in Laravel, making sure that only specific users can receive certain updates—in our case, order notifications.
We start by building a simple Order
model that belongs to a user, and set up the necessary database migration. Once we've got our order in place, we create an event for when an order is dispatched. The idea is to notify only the user who owns the order, not everyone that's logged in.
The magic happens in Laravel's channels.php
, where we define private channels—those can be based on the user's ID, which means broadcasts are scoped just to them. We wire up the event so that when an order is dispatched, it broadcasts only to the appropriate private channel using the user's ID.
Next, on the frontend (in this example, with Blade templates), we listen on the private channel by referencing the current user's ID. This ensures that only the rightful owner of the order gets the pop-up or notification. We also tackle a common gotcha: making sure Laravel's Broadcast Service Provider is enabled, so private channel authentication works as expected. With everything set up, we test it live—only the correct user receives the broadcasted event when their order is shipped.
Finally, we test by logging in as another user and confirm they don’t see the notification. This really shows how private channels keep broadcasts secure and targeted.
By the end of the episode, you’ll have a good grasp on how to set up and use Laravel’s private broadcast channels to deliver real-time events only to the users who should get them.