Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel broadcast notifications


Laravel broadcast notifications


Here's a concise answer to your query on broadcasting notifications in Laravel:

To broadcast notifications in Laravel, you can use the `broadcast` channel. First, ensure you have configured and are familiar with Laravel's event broadcasting services[1][2].

To format a broadcast notification, define a `toBroadcast` method on the notification class that returns a `BroadcastMessage` instance with the data to broadcast[1][2]:

php
use Illuminate\Notifications\Messages\BroadcastMessage;

public function toBroadcast($notifiable): BroadcastMessage
{
    return new BroadcastMessage([
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
    ]);
}

Broadcast notifications are queued by default. To configure the queue connection or name, use the `onConnection` and `onQueue` methods of `BroadcastMessage`[1][2]:

php
return (new BroadcastMessage($data))
    ->onConnection('sqs')
    ->onQueue('broadcasts');

Notifications are broadcast on a private channel formatted as `{notifiable}.{id}`. For example, a notification sent to `App\Models\User` with ID 1 will broadcast on the `App.Models.User.1` channel[2].

To listen for notifications in JavaScript using Laravel Echo, use the `notification` method[2]:

js
Echo.private(`App.Models.User.${userId}`)
    .notification((notification) => {
        console.log(notification.type);
    });

To customize the notification channel, define a `receivesBroadcastNotificationsOn` method on the notifiable entity[2]:

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

By implementing the `ShouldBroadcast` interface and defining a `toBroadcast` method, you can easily broadcast notifications from your Laravel application to real-time clients using Laravel's event broadcasting services.

Citations:
[1] https://laravel.com/docs/5.8/notifications
[2] https://laravel.com/docs/11.x/notifications
[3] https://stackoverflow.com/questions/75362269/broadcast-event-to-pusher-when-database-notification-is-created
[4] https://laracasts.com/discuss/channels/guides/laravel-notification-with-broadcasting
[5] https://christoph-rumpel.com/2020/11/laravel-real-time-notifications