How Do I

Listen for preference changes

React to user preference and context policy changes with Laravel events.

NotificationCompass dispatches NotificationPreferenceChanged whenever a stored preference or context policy changes. Use Laravel's event listeners to add application-specific auditing, real-time synchronization, external cache invalidation, or other business logic.

Register a listener

Create a listener for the package event:

app/Listeners/RecordNotificationPreferenceChange.php
namespace App\Listeners;

use NotificationCompass\Events\NotificationPreferenceChanged;

final class RecordNotificationPreferenceChange
{
    public function handle(NotificationPreferenceChanged $event): void
    {
        AuditLog::record([
            'notification' => $event->definition->key,
            'channel' => $event->channel,
            'context' => $event->context?->key(),
            'old_value' => $event->oldValue,
            'new_value' => $event->newValue,
            'change' => $event->change->value,
        ]);
    }
}

Register the listener in the application's event configuration according to its Laravel version. NotificationPreferenceChanged implements Laravel's ShouldDispatchAfterCommit, so listeners run only after the outermost database transaction commits. When no transaction is active, the event is dispatched immediately after the store persists the change.

If the transaction rolls back, the event is not dispatched. This guarantee applies when the store uses Laravel's event dispatcher and transaction manager. A custom persistence implementation that uses another transaction mechanism must provide the equivalent after-commit dispatch behavior itself.

Understand the payload

NotificationPreferenceChanged exposes the following fields:

  • notifiable: the user or other recipient for a user preference. It is null for a context policy.
  • context: the affected context, or null for a global user preference.
  • definition: the complete NotificationDefinition concerned by the change.
  • channel: the affected notification channel.
  • oldValue and newValue: the previous and resulting enabled values. A null value means that no explicit preference exists.
  • change: one of created, modified, reset, or deleted.
  • oldMode and newMode: the previous and resulting context policy modes when applicable.

User preference resets emit reset. Removing a context policy with forget emits deleted. Calling set with the same value and, for a context policy, the same mode does not emit an event.

The package does not automatically write audit records, broadcast events, or invalidate application-specific caches. Keep those decisions in the application's listeners.