Toti Cuervo
Toti Cuervo

Reputation: 285

Cannot access PrivateChannel

I am trying to implement a private channel for the first time on Laravel and VueJS. I have gotten to the point where the event triggers as expected, but I cannot listen to it in the component that I want it to.

I followed all the steps of installing the appropriate dependencies. Can someone please tell me why this might be?

My listener:

Echo.private('message')
                .listen('NewTeam', (e) => {
                    console.log('made it');
                });

My event:

namespace App\Events;

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

use Illuminate\Support\Facades\Log;


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

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public $team;

    public function __construct(Team $team)
    {
        $this->team = $team;
    }

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

    public function broadcastWith()
    {
        return ["message" => 'A new team has arrived'];
    }

My channel.php:

Broadcast::channel('message', function ($user) {
    return true;
});

My pusher account tells me that it is sending. However, when I trigger the event, I do not receive anything from the listener.

Upvotes: 0

Views: 59

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14271

It might be the event name that you are using. In your listener you are listening the "NewTeam" event on the message channel.

Echo.private('message')
        .listen('NewTeam', (e) => { // <---
            console.log('made it');
        });

But in your event you aren't specifying a custom event name. According to the docs:

Broadcast Name

By default, Laravel will broadcast the event using the event's class name. However, you may customize the broadcast name by defining a broadcastAs method on the event:

/**
 * The event's broadcast name.
 *
 * @return string
 */
public function broadcastAs()
{
    return 'server.created';
}

So this means that the event name used in your case propably is App\\Events\\NewTeam. In order to address/custom this the way you want, you'll need to add to your event class:

app/Events/NewTeam.php

/**
 * The event's broadcast name.
 *
 * @return string
 */
public function broadcastAs()
{
    return 'NewTeam';
}

Upvotes: 1

Related Questions