Pusher public events not getting read in the Frontend(react)

82 views Asked by At

I'm trying to make custom channel names using the pusher-php in my Laravel backend micro-service and I'm trying to read the events triggered on these channels on my React frontend.

This is how my event file looks like NewMessage.php:

<?php

namespace App\Events;

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

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

    public $message;
    public $player_id;

    public function __construct($message)
    {
        $this->message = $message;
        logger('NewMessage Event Triggered!');
    }

    public function broadcastOn()
    {
        return ['my-channel'];
    }

    public function broadcastAs()
    {
        return 'NewMessage';
    }
}

And I'm reading this event on the frontend with this code:

useEffect(() => {
    let channel = client.subscribe(['my-channel']);
    channel.bind("pusher:subscription_succeeded", () => {
      console.log("pusher:subscription_succeeded. Public channel = ", channel);
    })
    channel.bind('NewMessage', (e) => {
      console.log('New Event with name: NewMessage triggered. Event data = ', e);
    })
  }, []);

This whole setup is working alright as when I'm trying to achieve this using the channel name 'public' it's working fine and the events are getting read in the frontend. I'm facing this issue just when I change the name of the public channel.

1

There are 1 answers

3
Jeyhun Rashidov On

add this line to the top:

use Illuminate\Broadcasting\Channel;

and return Channel in the broadcastOn() method:

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

for more info you can look: https://petericebear.github.io/starting-laravel-echo-20170303/