You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Put this into event service providor's boot method
publicfunctionboot(): void
{
// Observe the DatabaseNotification model for created eventsDatabaseNotification::observe(newclass {
// Listen to the created event publicfunctioncreated(DatabaseNotification$notification): void
{
// Broadcast the notification to the user broadcast(newclass($notification) {
// Hold the notification in a property publicfunction__construct(publicDatabaseNotification$notification) {}
// Define the channel to broadcast the notification publicfunctionbroadcast()
{
// Get the proper channel name based on the notification type $channel = strtolower(class_basename(str($this->notification->type)->plural()));
// Broadcast to the notifiable model's private channel returnnewPrivateChannel($channel.'.'.$this->notification->notifiable_id);
}
// define the event name as it is anonymous classpublicfunctionbroadcastAs(): string
{
return'DatabaseNotificationCreated';
}
});
}
});
}
listen to the event like this
Echo.private('users.'+userId)// make sure to register your listener with a leading . character.listen('.DatabaseNotificationCreated',(e)=>{console.log(e.notification);});
bonus: in livewire
#[On('echo-private:customers.{customers.id},.DatabaseNotificationCreated')]
publicfunctionnotify($notification)
{
// Handle the notification here
}
Note: Don't forget to set authentication for the channel in routes\channels.php
You may create classes for observer and event both.