0

I'm using Laravel for backend and Vue for frontend. I'm also using Vite as my bundler and laravel echo for broadcasting. I'm trying to create a websocket to show newly added comments in real time.

this is the function for broadcasting in my app.vue:

    listenForNewComments() {
        window.Echo.channel('comments')
            .listen('CommentCreated', (e) => {
                this.newComments.push(e.comment);
                    console.log(e)
            });
    }

In my .env file I configured pusher information for vite:

VITE_PUSHER_APP_ID=1816356
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST=
VITE_PUSHER_APP_SECRET="${PUSHER_APP_SECRET}"
VITE_PUSHER_PORT=443
VITE_PUSHER_SCHEME=https
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

My bootstrap.js:

import axios from 'axios';
window.axios = axios;

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

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    forceTLS: true,
    encrypted: true,
});

channels.php:

Broadcast::channel('comments', function () {
    return true;
});

And this is the event `CommentCreated.php'

class CommentCreated implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $comment;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Comment $comment)
    {
        $this->comment = $comment;
    }

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

Obviosly I'm missing something and I tried to find a solution whole day. Function listenForNewComments I got from chatGPT and I'm sure that it made a mistake but I cannot find it. I found the same issue here but thread creator didn't even explained his solution. Please, help me!

1
  • hi, did you import class Broadcast to your CommentCreated.php' file?
    – TongaLife
    Commented Jun 10 at 12:40

0

Browse other questions tagged or ask your own question.