Laravel Echo never recieving event
Asked Answered
C

2

13

For whatever reason, I cannot receive any data on my client side from laravel echo. I am using laravel-echo-server (socket.io), redis broadcaster, and redis queues. As far as I can tell, they are all functional. I'll take you through how I set it up for testing. First I created a UserCreated event:

class UserCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

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

    public function broadcastAs()
    {
        return 'user.created';
    }
}

Then, to test this event, I created a CreateUser command:

class CreateUser extends Command
{
    protected $signature = 'create:user {username}';

    protected $description = 'Create a new user!';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $user = \Chatter\User::create([
            'name' => $this->argument('username'),
            'email' => uniqid() . '@gmail.com',
            'password' => bcrypt('secret')
        ]);
        event(new \Chatter\Events\UserCreated($user));
    }
}

Finally, here is my laravel-echo-server.json:

{
    "authEndpoint": "/broadcasting/auth",
    "authHost": "chatter.dev",
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "localhost"
        }
    },
    "port": 6001,
    "protocol": "http",
    "sslCertPath": "",
    "sslKeyPath": "",
    "socketio": {}
}

Next I ran php artisan queue:listen, and laravel-echo-server start. They both ran without error. To make sure that the server worked, I did php artisan create:user Bob123. It was successful. The queue returned this (in console):

[2017-06-01 01:28:27] Processing: Chatter\Events\UserCreated
[2017-06-01 01:28:27] Processed:  Chatter\Events\UserCreated

And the laravel-echo-server returned this (in console):

CHANNEL user-created

So, to get the data I sent with the user, I created a Vue component, with a echo listener in the mounted function. Here's my component:

<template>
    <div class="container">
        <div class="row">

        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
            window.Echo.channel('user-created')
                .listen('.user.created', (data) => {
                    console.log(data);
                });
        },

        data(){
            return {
                messages: []
            }
        }
     }
</script>

When I refreshed my webpage, Component mounted was logged to the console so I'm certain that it loaded. But, for whatever reason, when I send the CreateUser command, the data is not logged into the browsers console.

Here is everything that you might point out:

I changed my broadcast driver to redis in my .env

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

I also uncommented the BroadcastingServiceProvider in the app.php config.

I can't think of anything else right now that you might point out that I have done, but if I remember any others I will update the question.

Thanks for any help.

Note: I'm not familiar with Redis, so currently I'm leaning towards that being my problem. Simply adding predis\predis as a dependency simply doesn't feel like that's all I have to do. Hopefully this note helps.

Edit:

As suggested, I tried running redis-server before I ran laravel-echo-server. This is what was returned in the console:

vagrant@homestead:~/Code/Chatter$ redis-server
16342:C 01 Jun 05:45:38.066 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
16342:M 01 Jun 05:45:38.067 * Increased maximum number of open files to 10032 (it was originally set to 1024).
16342:M 01 Jun 05:45:38.067 # Creating Server TCP listening socket *:6379: bind: Address already in use

I assume this means that the redis server was running, so I guess homestead starts it automatically by default.

Github Repository:

Sorry this took so long, I was very busy personally. Here is the link to the github repository for this project. If there are any questions about the repository just let me know.

https://github.com/Dastur1970/laravel-echo-test

Edit 2:

Just in case anyone needs it, here is my the code I used to create my Echo instance.

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
    // auth: {
    //     headers: {
    //         'Authorization': 'bf242984230eb684 1076b91e572e5bbcc81a852471364c49'
    //     }
    // },
    // key: '1076b91e572e5bbcc81a852471364c497',
    // csrfToken: token.content
});

Commented out some of the stuff that I was testing with. Was not sure if I would need the again so I just left them commented. Let me know if any of the commented code may actually be helpful.

Civet answered 1/6, 2017 at 2:27 Comment(16)
Your redis server should be started before laravel-echo-serverBarbaraanne
@NehalHasnayeen Could you please elaborate on how I might do this?Civet
you run redis-server first and when it's up & running then start the laravel-echo-serverBarbaraanne
@NehalHasnayeen View my editCivet
try with this php artisan queue:work --sleep=1 and which port your laravel-echo-server is running?Barbaraanne
Just write console.log('test'); instead of logging data and see if that is working or not. based on that I can give you more information.Margherita
@NehalHasnayeen My laravel-echo-server is running on 6100 and php artisan queue:work --sleep=1 did the exact same thing as before (it arrived at the echo server and showed in the queue but didn't reach the client)Civet
@ParthVora I did console.log('test') and it still didn't appear.Civet
Try this in yours .env file: BROADCAST_DRIVER=redis CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync this is working for meMargherita
@Civet , you're saying laravel-echo-server is running on 6100 but in your laravel-echo-server.json file you're using 6001Barbaraanne
@NehalHasnayeen I'm sorry that's what I meantCivet
@ParthVora It still does the same thing.Civet
@dastur, that's weird. Is it a open source somewhere on github? I may be able to help you if I have fully running app.Margherita
@Dastur, i used database as a queue driver, you can try with thatBarbaraanne
@Dastur, can you please share the code on github? I'm pretty sure I can fix this if I can have a running app. I have a pretty similar working app like yours.Margherita
@ParthVora Github repository is above.Civet
M
2

I have setup your GIT repo on my local PC and got the issue.

You are using a custom namespace called "Chatter", so you have explicitly defined that in your JS code so that Echo can know that how to find that Event class.

So just change "UserCreated" with ".Chatter.Events.UserCreated" in public/js/app.js and you are good to go:

mounted: function mounted() {
        console.log('Component mounted.');
        console.log(window.Echo);
        window.Echo.channel('user-created').listen('.Chatter.Events.UserCreated', function (data) {
            console.log('tester123');
        });
    },

More info: https://laravel.com/docs/master/broadcasting#namespaces

Margherita answered 10/6, 2017 at 6:37 Comment(0)
L
2

Okay, let's find the possible parts where you error could be:

This is the queue that the server is running through

  1. Event
  2. Listener
  3. Redis
  4. Laravel-echo-Server
  5. Client

[2017-06-01 01:28:27] Processed: Chatter\Events\UserCreated

the event was successfully handled by the listener (step 2)

CHANNEL user-created

The event was written to the database and the laravel-echo-server got it (step 4)

Normally the laravel-echo-server prints a message when a new user joins a channel. I see none of those messages in your code so the connection between the laravel-echo-server and the client could be the problem. Also, I don't see any code where you create the Echo object on the client with Javascript.

Lineberry answered 4/6, 2017 at 6:5 Comment(3)
Your right it is strange that its not showing that users r joining the channel, but about the .user.created you prefix with a dot when you rename your event with the broadcastAs method in the event.Civet
never used boradcastas before, but after checking the official documentation I found the leading dot. Can you post your new Echo code where you init the connection to the server?Lineberry
I edited above with my code where I instantiated Echo.Civet
M
2

I have setup your GIT repo on my local PC and got the issue.

You are using a custom namespace called "Chatter", so you have explicitly defined that in your JS code so that Echo can know that how to find that Event class.

So just change "UserCreated" with ".Chatter.Events.UserCreated" in public/js/app.js and you are good to go:

mounted: function mounted() {
        console.log('Component mounted.');
        console.log(window.Echo);
        window.Echo.channel('user-created').listen('.Chatter.Events.UserCreated', function (data) {
            console.log('tester123');
        });
    },

More info: https://laravel.com/docs/master/broadcasting#namespaces

Margherita answered 10/6, 2017 at 6:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.