Laravel echo with socket.io

Parth Vora picture Parth Vora · Jan 13, 2017 · Viewed 8.2k times · Source

I want to listen for server side event on javascript side. I found this package for that:

https://github.com/tlaverdure/laravel-echo-server

I have already read all if this so many times:

https://laravel.com/docs/5.3/events

https://laravel.com/docs/5.3/broadcasting

https://laravel.com/docs/5.3/notifications

So far I have done this:

Controller action:

broadcast(new NewVote());
event(new NewVote()); // Also tried this

"NewVote" Event class:

public function broadcastOn()
    {
        return new Channel('new-vote');
    }

Javascript:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://assessment.local:6001'
});

window.Echo.channel('new-vote')
    .listen('NewVote', (e) => {
        console.log(e);
    });

laravel-echo-server.json

{
    "appKey": "0p4o9t942ct15boc4nr8tjb178q29fdmlcat8c1p1s51i2pbq9nmtjud94t4",
    "authHost": null,
    "authEndpoint": "/broadcasting/auth",
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "assessment.local",
    "port": "6001",
    "referrers": [],
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

Already this commands are running:

laravel-echo-server start
php artisan queue:work
php artisan queue:listen
gulp watch

All I'm expecting a console massage when, I fire the event. But I'm not getting anything on the console.

Let me know if any other information needed.

Note: My socket.io server is running successfully without any error.

Thanks,

Parth Vora

Answer

Eelke van den Bos picture Eelke van den Bos · Jan 13, 2017

Configuring Echo took me a while, but I found the client side configuration to contain a confusing default event namespace.

Try configuring the Echo client side library as following:

import Echo from "laravel-echo"

window.Echo = new Echo({
    namespace: 'Base.Event.Namespace', //defaults to App.Event
    broadcaster: 'socket.io',
    host: 'http://assessment.local:6001'
});

So when firing an event like so event(new \Hello\World\NewVote()), make sure Echo is configured with the namespace Hello.World

Cheers!