Reputation: 41
I am trying to create a real-time chat application. I used Laravel Echo, Redis, and socket-io.
But laravel-echo
is not listening to private broadcast chat channel.
App\Events\MessagePushed
public function broadcastAs()
{
return 'new.message';
}
public function broadcastOn()
{
return new PrivateChannel("application-chat-{$this->message->job_application_id}");
}
routes/channels.php
Broadcast::channel('application-chat-{job_application_id}', function ($user, $job_application_id) {
return auth()->check();
});
Store Message resource method
public function store(StoreFormRequest $request, JobApplication $application)
{
$request->merge([
'sender_id' => $request->user()->id,
]);
$message = $application->messages()->create($request->all())
->load(['sender', 'receiver']);
event(new MessagePushed($message));
return response()->json([
'message' => $message,
]);
}
Listening to private channel
window.Echo.private(`application-chat-${this.messageApplication}`)
.listen('.new.message', (data) => {
console.clear();
console.log('Got event...', data);
});
Upvotes: 4
Views: 4235
Reputation: 161
I think the problem is with the namespace
window.Echo = new Echo({
namespace: 'App.Events',
});
Upvotes: 0
Reputation: 2683
Hope it will help to debug:
Laravel echo server config:
{
"authHost": "domain.local",
"authEndpoint": "/broadcasting/auth",
"database": "redis",
"databaseConfig": {
"redis": {}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
php artisan queue:work:
Check that queue sends events
laravel echo server
Check that user joins channel and echo server sends events
Laravel Echo:
Maybe problem with broacastAs. Try to not use it. Don't forget to add namespace property to config.
window.Echo = new Echo({
namespace: 'App.Events',
broadcaster: 'socket.io',
host: window.location.protocol + '//' + window.location.hostname + ':6001',
auth: {
headers: {
Authorization: //auth
}
}
});
Name of Event = Name of Event class
window.Echo.private(`application-chat-${this.messageApplication}`)
.listen('MessagePushed', (data) => {
console.log(data);
});
Upvotes: 2