Listen for preference changes
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:
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 isnullfor a context policy.context: the affected context, ornullfor a global user preference.definition: the completeNotificationDefinitionconcerned by the change.channel: the affected notification channel.oldValueandnewValue: the previous and resulting enabled values. Anullvalue means that no explicit preference exists.change: one ofcreated,modified,reset, ordeleted.oldModeandnewMode: 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.