Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Created February 11, 2024 13:27
Show Gist options
  • Save MrPunyapal/019164398245598ae99a4213f779fdcb to your computer and use it in GitHub Desktop.
Save MrPunyapal/019164398245598ae99a4213f779fdcb to your computer and use it in GitHub Desktop.
Optimal method for swiftly broadcasting database notifications in Laravel

Put this into event service providor's boot method

public function boot(): void
{
    // Observe the DatabaseNotification model for created events
    DatabaseNotification::observe(new class {
        
        // Listen to the created event 
        public function created(DatabaseNotification $notification): void
        {
            // Broadcast the notification to the user 
            broadcast(new class($notification) {
                
                // Hold the notification in a property 
                public function __construct(public DatabaseNotification $notification) {}
                
                // Define the channel to broadcast the notification 
                public function broadcast()
                {
                    // 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 
                    return new PrivateChannel($channel.'.'.$this->notification->notifiable_id);
                }

                // define the event name as it is anonymous class
                public function broadcastAs(): 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')]
public function notify($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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment