Jayant Dahiya
Jayant Dahiya

Reputation: 1

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

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.

Upvotes: 0

Views: 307

Answers (1)

Jeyhun Rashidov
Jeyhun Rashidov

Reputation: 1128

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/

Upvotes: 0

Related Questions