Up to this point we have always worked with public channels in Laravel Echo. Public channels can be useful for websites with public facing frontends and with notifications like comments that don't provide sensitive or private information.
So what do you do when your channels are distributing information that is only intended for certain users (like admins or managers) or the author of a blog post, or the information being sent is more sensitive? Well that is when we use private channels, which require users to authenticate in order to subscribe to a channel.
There are three basic steps needed to convert a channel from a public channel to a private one:
- In your
App\Events
file we need to changereturn new Channel('post')
toreturn new PrivateChannel('post')
inside thebroadcastOn()
method. - On the client side (which for us is on the
posts.show
blade file) we need to tell laravel echo that we are subscribing to a private channel now. This means changingEcho.channel()
toEcho.private()
. Everything else can stay the same. - Lastly, in our
routes/channels.php
file we can define our private channel with authentication rules by ensuring that the function returns true or false to determine the user's eligibility for that private channel.