3

I am using event broadcasting in Laravel. I am using role based access to notifications. I have custom auth guard for broadcasting. When user connects to channel client sends access_token with permissions inside to server. Server validates this access_token and allow connection (I use 3d party service Auth0 for authenticating users, it means that each time user connects to each broadcast channel, it takes some time for validating token on server side).

I have multiple events in my app which I want to broadcast. Should I have to create multiple private channels (one per event) for each user, like:

window.Echo.private('channel1'+user_id)
  // This channel can translate only one event - "firstEvent"
  .listen("firstEvent", (mes) => {
      console.log(mes);
})
window.Echo.private('channel2'+user_id)
  // This channel can translate only one event - "secondEvent"
  .listen("secondEvent", (mes) => {
      console.log(mes);
})
// etc.

Then on server side I check (in closure at routes/channels.php) if the user have permission for this channel or not, and allow or forbid him to connect to channel. And when event fired, in its broadcastOn I do something like:

public function broadcastOn()
{
    $users_from_db = \App\NotificationUsers::where('permission',$this->permission)->get();
    foreach($users_from_db as $user){
        return new PrivateChannel('connections'.$user->id); 
    }

}
// Permission for each event is defined in each event class as private property.

Thus every user on initial page load try to connect to multiple channels, and if he allowed, he receive notifications, not allowed - not receive.

Or

I should create a single channel:

window.Echo.private('singleChannel.'+user_id)
  .listen("Event1", (mes) => {
      console.log(mes);
})
window.Echo.private('singleChannel.'+user_id)
  .listen("Event2", (mes) => {
      console.log(mes);
})

or... any other variant? What is a good practice?

John Smith
  • 1,204
  • 3
  • 22
  • 42

1 Answers1

1

The broadcastOn method returns Channel or array, in your "foreach" you must not use "return" you should fill an array objects of private channels for each user after "foreach" you must return the array.

public function broadcastOn()
{
   $users_from_db = \App\NotificationUsers::where('permission',$this->permission)->get();
   $channels = [];
   foreach($users_from_db as $user){
       $channels[] = new PrivateChannel('connections'.$user->id); 
   }

   return $channels;

}

TohidHabiby
  • 186
  • 4