Laravel Livewire Echo configuration

Viewed 1131

I've setup a notification system with Pusher and Echo on my Laravel 8 app. It works fine, I'm able to retrieve the notification event in VanillaJS with

window.Echo.private('App.Models.User.' + User.id)
.notification((notification) => {
    if (notification.type === 'App\\Notifications\\JobLiked') {
        let count = document.getElementById('count');
        let number = count.innerHTML;
        number++;
        count.innerHTML = number;
    }
});

But now I want to use Livewire listeners to trigger my function, then I setup :

public function getListeners()
{
    return [
        "echo-private:App.Models.User.{$this->authId},NotificationSent" => 'notifyNewJobLiked',
    ];
}

But nothing seems to work and I have no error message.. do you have any clue what could possibly going on ?

Thank you very much ! :)

2 Answers

Try to configure your listener with the following specific event name:

public function getListeners()
{
    return [
        "echo-private:App.Models.User.{$this->authId},.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated" => 'notifyNewJobLiked',
    ];
}

Since you are using Laravel Notifications to trigger the broadcast instead of a broadcastable event, the event name when fired defaults to Illuminate\\Notifications\\Events\\BroadcastNotificationCreated.

In Echo there are two methods to listen for incoming messages: notification and listen. The reason why it works with your vanilla js is that you are using the notification method, whereas the livewire event listener only works with Echo's listen, which expects the name of the calling event.

If you are using pusher, you can see the name of the calling event in the pusher debug console.

Also take care and add a dot in front of the namespaced event as described in the documentation.

Right way to get Echo notification in livewire:

public function getListeners()
    {
        $user_id = auth()->user()->id;

        return [
            "echo-notification:App.Models.User.{$user_id}, notification" => 'gotNotification'
        ];
    }

As you can see the channel type is notification, not private:

echo-notification

Also don't forget to have a record authenticating the users in your channels route, same as you do for a private channel:

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Another thing I learned is that you can get the notification channel data from the returned field. So you can do:

public function gotNotification($notification)
{
    
}
Related