javascriptlaraveltypescriptwebsocketlaravel-websockets

Laravel Echo not listening channels


I use laravel Echo with Vue and Quasar Framework. On backend: Laravel 9 and Laravel Websockets (php). Websockets server working, authentication completed, in Chrome "Network" tab i see websocket connection. All messages in "Network" tab recieved, in Laravel Websockets debug page i see "subscribed 785317453.777403975 Channel: test" (my browser), but this code, not working.

Websocket boot file:

  import { boot } from "quasar/wrappers";
import Echo from "laravel-echo";
import { useUserStore } from "stores/user/user-store";

let echo: Echo;

// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/boot-files
export default boot(async () => {
  const { user: currentUser } = useUserStore();

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  window.Pusher = require("pusher-js");

  const echo = new Echo({
    broadcaster: "pusher",
    authEndpoint: "http://127.0.0.1:8000/broadcasting/auth",
    key: "laravel_key",
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    auth: {
      params: {
        withCredentials: true
      },
      headers: {
        Authorization: "Bearer " + currentUser.websocket_token
      }
    }
  });

  echo.channel('test').listen('test', (e: object| string) => {
    console.log(e);
    console.log('test');
  });
  echo.private("App.Models.User.1")
    .listen("App\Events\TestEvent", (e: object | string) => console.log(e));
});

export { echo };

TestEvent file

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    public function broadcastWith()
    {
        return ['message' => 'test'];
    }

    public function broadcastOn(): Channel
    {
        return new PrivateChannel('App.Models.User.1');
    }
}

messages received from server data from websockets debug page

Why in "listen" methods not receieved message?


Solution

  • You can listen on

    echo.private('channel_name')
     .listen('event_classname in your case TestEvent', 
       (e) => {}
     )
    

    And for public channels it is the same thing just change the private function to channel and also in the event class change the PrivateChannel to Channel, it should work the same, but without authorization.