I'm attempting to use laravel-echo-server (socket.io) I'm getting a roadblock where the client-side doesn't appear to be getting any broadcasted events.
Everything seems to be connected fine and socket.io server is reporting that it's connecting and authorising the user however when I broadcast a message nothing seems to happen. The event is appearing on Laravel Horizon but otherwise, nothing happens. Here is my code:
server.js to run the laravel-echo-server:
require('dotenv').config();
const env = process.env;
require('laravel-echo-server').run({
authHost: env.APP_URL,
devMode: env.APP_DEBUG,
database: "redis",
databaseConfig: {
redis: {
host: env.REDIS_HOST_PUBLIC,
port: env.REDIS_PORT,
}
}
});
My channel in channel.php
Broadcast::channel('message.pushed', function () {
return true;
});
My event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessagePushed implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
$this->message = "My New Message";
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('message.pushed');
}
}
My event listener within app.js
import Echo from 'laravel-echo';
window.io = require('socket.io-client');
if (typeof io !== 'undefined') {
var token = $('meta[name="_token"]').attr('content')
window.Echo = new Echo({
auth : {
headers: {
Authorization: `Bearer ${token}`,
},
},
broadcaster: 'socket.io',
host : window.location.hostname + ':6001',
});
}
function listenForBroadcast() {
Echo.private('message.pushed')
.listen('MessagePushed', (e) => {
console.log(e)
console.log("Listened")
});
}
listenForBroadcast();
Lastly the route sending the message:
Route::get('/event-test', function () {
broadcast(new App\Events\MessagePushed());
});
I am not quite sure where i have gone wrong or why nothing is being picked up by the client.
While looking in laravel-echo-server the command line is echoing:
Channel: laravel_database_private-message.pushed
Event: App\Events\MessagePushed