0
votes

My events are receiving at the pusher like-

Event - API message

Details - Channel: private-chat, Event: App\Events\MessageSent

But in my Vue frontend, Echo is not receiving any events from pusher.

MessageSent.php

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

    public $message;
    public $user;

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

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

chat.vue

  mounted() {
    Echo.private("chat").listen("MessageSent", (e) => {
      console.log("Received");
      this.allMessages.push(e.message);
      this.fetchMessages();
    });
  },

bootstrap.js

import Echo from 'laravel-echo';

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

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true,
});

routes/channels.php

Broadcast::channel('chat', function ($user) {
    return auth()->check();
});

I have also set up broadcast driver = pusher & all the pusher credentials in my .env file

2
Have you added authorization logic in routes\channels.php?Tun Nanda Aung
Yes, I updated the questionDebarshi Das
Did you see any error in your dev tool?Tun Nanda Aung
There is no error.Debarshi Das

2 Answers

0
votes

In MessageSent event do this

public function broadcastOn()
{
    Broadcast::routes(['middleware' => ['auth:api']]);
    return new PrivateChannel('chat');
}

And in BroadcastServiceProvider add the following line:

Broadcast::routes(['middleware' => ['auth:api']]);
0
votes

I have solved this by putting the below code from bootstrap.js to app.js. So, in my app.js -

import Echo from 'laravel-echo';

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

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true,
});

But I don't know why the same code is not working in bootstrap.js