LorienDarenya's avatar

Laravel Echo Not Listening

At least, that's what I assume is happening. I have been following this tutorial: https://pusher.com/tutorials/chat-laravel/ and everything works great up until I try to make it realtime. At this point, I can send and receive messages, but have to refresh to get them. Any help is appreciated.

bootstrap.js


window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

 import Echo from 'laravel-echo'

 window.Pusher = require('pusher-js');
 Pusher.logToConsole = true;

 window.Echo = new Echo({
     broadcaster: 'pusher',
     key: 'MyCorrectPusherKey',
     cluster: 'mt1',
     encrypted: true
 });

app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));
Vue.component('chat-messages', require('./components/ChatMessages.vue'));
Vue.component('chat-form', require('./components/ChatForm.vue'));

const app = new Vue({
    el: '#app',

    data: {
        chat_messages: []
    },

    created() {
        this.fetchChatMessages();
      Echo.private('chat')
        .listen('ChatMessageSent', (e) => {
          this.chat_messages.push({
            message: e.message.body,
            user: e.user
          });
        });
    },

    methods: {
        fetchChatMessages() {
            axios.get('/chitterings/chat/messages').then(response => {
                this.chat_messages = response.data;
            });
        },

        addChatMessage(message) {
            this.chat_messages.push(message);

            axios.post('/chitterings/chat/send', message).then(response => {
              console.log(response.data);
            });
        }
    }
});

ChatMessageSent.php

<?php

namespace App\Events;

use App\Models\Chat;
use App\Models\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class ChatMessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * User that sent the message
     *
     * @var User
     */
    public $user;

    /**
     * Message details
     *
     * @var Message
     */
    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user, Chat $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat');
    }

}

I can see the payload for the event in my debug console on pusher, but no subscription or occupation, etc.

0 likes
11 replies
LorienDarenya's avatar

I tried using log as my driver and received the event in my log. Again, I also see an event in my debug console at Pusher when .env has pusher as the broadcast driver. Any help? I am really at my whits end here!

mezie's avatar

Is the app cluster also specified in broadcast.php?

LorienDarenya's avatar

I'm using 5.6 which seems to have the app cluster defined in .env. I have double and tripple checked that it is mt1 as specified. <3

mezie's avatar

Setup queue to listen and fire the event?

LorienDarenya's avatar

I have tried this. Nothing appears. I have to wonder if I'm doing something wrong. I have tried with php artisan queue:listen and php artisan queue:work both. I can give you a login to see the app live if necessary; I really appreciate you trying to help. I'm just so out of ideas.

ederson's avatar

localStorage.debug = '*';

Type this in console. Helped me a lot finding problems with Socket and echo

LorienDarenya's avatar

I finally teased this out of my javascript console, but I have absolutely no idea what it means:

[Info] You are running Vue in development mode. (app.js, line 45689)
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
[Log] Pusher : State changed : connecting -> connected with new socket ID 240641.22778865 (app.js, line 33100)
[Log] Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"9219a41a3592c87a315b:c932cc150eeeedc3167e4a952bcb4a2773c795f0c0483acc98de4bdf37a9d744","channel":"private-chat"}} (app.js, line 33100)
[Log] Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"private-chat"} (app.js, line 33100)
[Log] Pusher : No callbacks on private-chat for pusher:subscription_succeeded (app.js, line 33100)
[Log] {status: "Message Sent!"} (app.js, line 1139)
LorienDarenya's avatar

Further more, when I try logging some info to laravel.log when the event is broadcast, this works just fine. It's so strange that realtime functionality simply isn't working at all.

LorienDarenya's avatar

So at this point, I'm wondering if it's something to do with pusher. I even created a new app, with an entirely different setup, and the realtime functionality isn't working there, either.

ederson's avatar

I m in on the phone so I am maybe missing something but it looks like you are broacasting an event but you are listening a private channel

LorienDarenya's avatar

I am indeed listening on a private channel as per the tutorial. Further more, no matter what environment I'm on, I can't seem to get the straight-up source code to work. This is on a Mac and on Centos 7 respectively. If anyone has any idea at all I'd be enormously grateful.

Please or to participate in this conversation.