I'm trying to join a Presence channel using Javascript's library Echo. I can successfully join the regular channel.
So, this is what I did:
I fire the event like this:
event(new FixtureChatroomEvent($userId, $message, $username, $profileImg, $fixtureId));
or like this
broadcast(new FixtureChatroomEvent($userId, $message, $username, $profileImg, $fixtureId))->toOthers();
The event looks like this (It looks ugly, I know, I will pass in a class later on):
class FixtureChatroomEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $username;
public $profileImg;
public $userId;
public $fixtureId;
public function __construct($userId, $message, $username, $profileImg, $fixtureId)
{
$this->message = $message;
$this->username = $username;
$this->profileImg = $profileImg;
$this->userId = $userId;
$this->fixtureId = $fixtureId;
}
public function broadcastOn()
{
return new PresenceChannel('fixture-channel.' . $this->fixtureId);
}
}
The listener method is simple, I only use handle method that looks like this:
public function handle(FixtureChatroomEvent $event)
{
return $event;
}
It is also registered in EventServiceProvider
like this :
'App\Events\FixtureChatroomEvent' => [
'App\Listeners\FixtureChatroomEventListener'
],
channels.php (route) looks like this:
Broadcast::channel('fixture-channel.{fixtureId}', function ($user, $message, $username, $profileImg, $userId, $fixtureId) {
return [
'message' => $message,
'username' => $username,
'profileImg' => $profileImg,
'userId' => $userId,
'fixtureId' => $fixtureId
];
});
And BroadcastServiceProvider
looks like this:
public function boot()
{
Broadcast::routes(['middleware' => ['auth:api']]);
require base_path('routes/channels.php');
}
Now the front end: I simply try to do something like this (I pass in the fixtures ID to the part of the channel name which is the same as the Events fixtureId
- the channel name is correctly output):
$(document).ready(function(){
var fixtureChannel =`fixture-channel.${$('#fixture_id').text()}`;
//var fixtureChannel = 'fixture-channel';
console.log(fixtureChannel);
Echo.join(fixtureChannel)
.listen('FixtureChatroomEvent', (e) => {
alert('ok');
console.log('ok');
})
.here((users) => {
console.log('123');
})
.joining((user) => {
console.log(user.name);
})
.leaving((user) => {
console.log(user.name);
})
;
});
Now the event is fired, but nothing is seen on the other side. I also tried joining the presence channel with no fixtureId, no success. No errors are shown. How can I even debug this?
The packages debugger (laravel-websockets) shows that the event was fired, but no connections are seen:
The problem was the Broadcast::routes(['middleware' => ['auth:api']]);
line. I removed the middleware, like this: Broadcast::routes();
I tried this before posting this question, but for the first time, the server returns a 500 error. Simply refreshing the page again helped.