Broadcast Channel
The broadcast channel broadcasts notifications in real-time to frontend clients via Server-Sent Events (SSE) or WebSockets using jengo/broadcasting.
The BroadcastMessage Builder
Define a toBroadcast() method returning a Jengo\Notifications\Messages\BroadcastMessage:
php
namespace App\Notifications;
use Jengo\Notifications\Messages\BroadcastMessage;
use Jengo\Notifications\Notification;
class NewCommentPosted extends Notification
{
public function __construct(public array $comment)
{
parent::__construct();
}
public function via(object $notifiable): array
{
return ['broadcast', 'database'];
}
public function toBroadcast(object $notifiable): BroadcastMessage
{
return (new BroadcastMessage([
'id' => $this->id,
'title' => 'New Comment',
'author' => $this->comment['author'],
'body' => $this->comment['text'],
'post_id' => $this->comment['post_id'],
'created_at' => date(DATE_ATOM),
]))
->event('comment.created')
->channel("private-user.{$notifiable->id}");
}
}Frontend Integration
When dispatched, frontend applications running the @jengo/broadcasting client immediately receive the event without polling:
typescript
import { createBroadcastClient } from '@jengo/broadcasting';
const client = createBroadcastClient({
endpoint: '/broadcasting/events',
});
// Listen on the user's private channel
client.channel(`private-user.${userId}`)
.listen('comment.created', (event) => {
// Display toast alert or update UI counter
showToast(event.title, event.body);
});