Laravel Livewire: Private notifications with Echo (pusher.js)

Photo by Mark König on Unsplash

Laravel Livewire: Private notifications with Echo (pusher.js)

In the docs for Livewire there's an example for handling events via Echo but took me a bit to figure out how to use just the basic notification on a User model.

Turns out it is really dang simple (thanks Caleb!).

In your component that will be the listener for an event you can use:

// Special Syntax: ['echo:{channel},{event}' => '{method}']
protected $listeners = ['echo:orders,OrderShipped' => 'notifyNewOrder'];

Now to listen for something like $user->notify(new OrderReady());

First, add to your User.php model:

    public function receivesBroadcastNotificationsOn(): string
    {
        return 'users.'.$this->id;
    }

A paired down version of our component:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Notification extends Component
{
    public function getListeners(): array
    {
        $authId = auth()->id();
        return [
            "echo-private:users.{$authId},.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated" => 'sendNotify',
        ];
    }

    public function sendNotify(mixed $notify): void
    {
        // Do things!
    }
}

We've added this to the bottom of our layout blade. You can include the normal render() to do popups or whatever is needed.

Thanks, for reading, please let me know if you found this helpful or have questions over on Twitter: twitter.com/DigiGuyDev or in the comments below!

P.S.

If you start getting 403 errors in the console about /broadcast/auth make sure to read the docs.