How Do I

Use contextual preferences

Store user preferences and policies for an organization, team, project, or another scope.

Create a NotificationContext and pass it to the fluent selection:

$context = new NotificationContext('team', $team->getKey());

$user->notificationPreferences()
    ->for('incident.created', $context)
    ->disable('mail');

Context values take precedence over global values. During delivery, implement notificationContext on the notification or bind a custom NotificationContextResolver.

The default context key for this example is team:12 when the team identifier is 12.

Apply a context policy

Use NotificationContextPreferenceManager when an organization, team, community, or workspace administrator must apply a preference to every member of a context:

app/Actions/SetContextNotificationPolicy.php
use NotificationCompass\Managers\NotificationContextPreferenceManager;
use NotificationCompass\ValueObjects\NotificationContext;
use NotificationCompass\ValueObjects\NotificationContextPreferenceMode;

$administrator = auth()->user();

app(NotificationContextPreferenceManager::class)->set(
    $administrator,
    new NotificationContext('organization', $organizationId),
    'incident.created',
    'mail',
    false,
    NotificationContextPreferenceMode::DEFAULT,
);

Use NotificationContextPreferenceMode::DEFAULT for a preference that users can override. Use NotificationContextPreferenceMode::ENFORCED to prevent overrides:

app/Actions/EnforceContextNotificationPolicy.php
app(NotificationContextPreferenceManager::class)->enable(
    $administrator,
    new NotificationContext('organization', $organizationId),
    'incident.created',
    'mail',
    NotificationContextPreferenceMode::ENFORCED,
);

Read and inspect policies through the same manager:

$manager = app(NotificationContextPreferenceManager::class);

$policy = $manager->get($administrator, $context, 'incident.created', 'mail');
$policies = $manager->inspect($administrator, $context);

Remove a policy with reset when the context should return to its member preferences:

app/Actions/RemoveContextNotificationPolicy.php
app(NotificationContextPreferenceManager::class)->reset(
    $administrator,
    new NotificationContext('organization', $organizationId),
    'incident.created',
    'mail',
);

The manager validates the administrator, notification definition, channel, supported context types, and mandatory channels before calling the store. The default Eloquent store uses the context key and does not require a domain model. Bind MutableNotificationContextPreferenceStore to a custom store when the application uses another persistence layer.