1

I have chat rooms that for now are one-to-one chats between two users.

This is the channel without authorization

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
     return ['id' => $user->id, 'name' => $user->name];
});

This way it works, but I wanted to change it to something like this so it can check if you are either sender or receiver in the room otherwise you are not allowed.

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
      if ($user->canJoinRoom($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
      }
});

and this is the canJoinRoom method in the User's model

public function canJoinRoom($roomID) {
        $room = MessageRoom::findOrFail($roomID);

        if($room){
            if(auth()->user()->id == $room->user_id || auth()->user()->id == $room->receiver_id){
                return $this->room_id == $roomID;
            }else{
                return false;
            }
        }else {
            return false;
        }
    }

With that, I get broadcasting/auth 404 Not found, when I try to use the user's method and check additional stuff.

Also tried this way, but I still get broadcasting/auth 404 Not found.

if ($user->id === MessageRoom::findOrFail($roomId)->user_id || $user->id === MessageRoom::findOrFail($roomId)->receiver_id) {
        return ['id' => $user->id, 'name' => $user->name];
    }
CritingZ
  • 388
  • 2
  • 16
  • The problem is in `findOrFail()`. If the MessageRoom is not found, the rest of your code will never reach as it fails on a 404. You have to check the values separated and continue from there. – Dimitri Mostrey Jan 03 '21 at 10:50
  • I checked with specific ID and did dd on the result. the room is found, it returns true, but once I remove the dd, it's 404 not found.. – CritingZ Jan 03 '21 at 10:56
  • my mistake, it all works not. I also checked by ID, but I was passing the unique code of the room. Thank you. – CritingZ Jan 03 '21 at 11:00

0 Answers0