sameoldnick / laravel-notification-preferences
A Laravel package for managing user notification preferences by notification type and delivery channel.
Package info
github.com/SameOldNick/laravel-notification-preferences
pkg:composer/sameoldnick/laravel-notification-preferences
Requires
- php: ^8.4
- illuminate/contracts: ^11.0||^12.0||^13.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/fortify: ^1.37
- laravel/pint: ^1.30
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.0.0||^10.0.0||^9.0.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-arch: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- spatie/laravel-ray: ^1.35
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Let users choose which channels each type of notification is delivered through, while guaranteeing that important notifications always reach them.
Table of Contents
Requirements
- PHP 8.4 or higher
- Laravel 11, 12, or 13
- Composer
Installation
Install the package with Composer:
composer require sameoldnick/laravel-notification-preferences
Publish the configuration file and the migration:
php artisan vendor:publish --tag=notification-preferences-config php artisan vendor:publish --tag=notification-preferences-migrations
Run the migration:
php artisan migrate
Add the HasNotificationPreferences trait to the notifiable model, usually your User model:
<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use SameOldNick\NotificationPreferences\Concerns\HasNotificationPreferences; class User extends Authenticatable { use HasNotificationPreferences; // ... }
Configuration
The published configuration file is config/notification-preferences.php.
Channels
Three top-level keys configure channels; available_channels is optional:
channels— the registry of channels the application can offer, each with a label and an optionalenabled_by_defaultflag.available_channels— an optional subset ofchannelskeys that users can enable or disable. When omitted, every registered channel is offered; an explicit empty array offers none.required_channels— the channels that are always sent, regardless of user preferences. Users cannot disable these.
<?php // config/notification-preferences.php return [ 'channels' => [ 'mail' => [ 'label' => 'Email', ], 'database' => [ 'label' => 'In-app', ], 'ntfy' => [ 'label' => 'Ntfy', 'enabled_by_default' => false, ], ], // Optional: omit this to offer every channel registered above. 'available_channels' => [ 'mail', 'database', 'ntfy', ], 'required_channels' => [ 'database', ], ];
- Channel keys must match the channel names your notifications return from
via(), such asmail,database,broadcast, or a channel class name. - Labels may be plain strings or translation keys.
enabled_by_defaultsets the state used when the notifiable has no stored preference for that channel. It affects both the preferences list and delivery, and an omitted value means enabled. Required channels ignore it.available_channelsonly narrows the registry. Every value must be a key ofchannels; naming an unregistered channel throws anInvalidArgumentExceptionwhen the catalog resolves it. Omit the key to offer everything, or use[]to offer nothing.- A required channel does not have to appear in
available_channelsor inchannels; it is appended to the resolved channels either way. - The published file contains example values. Replace them with the channels your application actually sends through, and only list required channels your application can deliver.
Note:
channelsprovides display metadata (used byNotificationCatalog::notificationChannels()) and the per-channel default state.available_channelsoptionally narrows which of them are offered, andrequired_channelscontrols which are forced.
Notification types
Each notification type is keyed by the value returned from its notificationType() method (or from its NotificationType attribute) and defines a label and a category. Both may be translation keys.
'types' => [ 'my-notification' => [ 'label' => 'My Notification', 'category' => 'General', ], ],
Guarding notification types
Some types only apply to certain notifiables, based on roles, permissions, or a plan. Configure a single guard for the whole catalog; it is asked about every configured type:
'guard' => App\Notifications\NotificationGuard::class,
<?php namespace App\Notifications; use SameOldNick\NotificationPreferences\Contracts\NotificationTypeGuard; class NotificationGuard implements NotificationTypeGuard { public function allows(string $notificationType, object $notifiable): bool { return match ($notificationType) { 'billing_failed' => $notifiable->hasRole('billing'), default => true, }; } }
- The guard is resolved from the container, so it may declare constructor dependencies. Bind it as a singleton if constructing it is expensive.
- Set
guardtoNotificationTypeGuard::classto resolve the implementation bound to the contract instead of naming a concrete class. Configuring the contract without a binding throws anInvalidArgumentException. - A missing or
nullguard leaves every type unguarded. Any other value that is not a class-string implementing the contract throws anInvalidArgumentException. - Use a class-string rather than a closure, so
config:cachecan still serialize the configuration. - Guarded-out types are omitted from
getPreferencesForNotifiable()andgetNotificationTypesForNotifiable(), and rejected byupdatePreferencesForNotifiable(). - Guarded-out types are not delivered either.
via()resolves no channels for them, and required channels are not appended to override the guard. - The guard runs for each type and notifiable, both when listing preferences and when resolving channels during delivery, so keep it cheap. Because delivery can happen in a queue worker, the guard must not depend on request-only state such as the session; use the notifiable it receives, for example with
Gate::forUser($notifiable).
To use a Gate or policy, call it from the guard:
public function allows(string $notificationType, object $notifiable): bool { return Gate::forUser($notifiable)->allows('receive-notification-type', $notificationType); }
Per-type channel overrides
A notification type may override the global channel lists:
'types' => [ 'security-alert' => [ 'label' => 'Security Alert', 'category' => 'Security', 'available_channels' => ['mail', 'database'], 'required_channels' => ['mail'], 'default_channels' => ['mail'], ], ],
- Omitting a key or setting it to
nullfalls back to the matching global list. - An empty array opts out of the global list. For example,
'required_channels' => []means no channel is forced for that type. default_channelsoverrides the channel defaults for that type: omitted ornullfalls back to each channel'senabled_by_default, while[]disables every channel by default for the type.- Overrides only apply to the type that declares them.
- A type with no available channels (global or overridden) produces no preference entries.
How the channel list is resolved
When a notification that uses RoutesViaNotifiablePreferences is sent, its channels are resolved in this order:
- If the configured guard rejects the notification type for the notifiable, resolve no channels at all. Required channels do not override this.
- Start with the available channels for the notification type: its own
available_channelsoverride, otherwise the global list, otherwise every key inchannels. - Remove channels the notifiable has disabled, and channels that are disabled by default and have no stored preference.
- Append the required channels for the notification type.
- Remove duplicates.
A channel with no stored preference follows its default state: enabled unless enabled_by_default (or the type's default_channels) turns it off. Newly added channels therefore still reach existing users unless they are opt-in. Saving a preference writes an explicit row for the submitted channels, which then stops following later default changes. Required channels are appended either way.
The guard runs during delivery as well as when listing preferences. A guarded-out type resolves no channels, so the notification is dispatched but nothing is delivered; choose recipients deliberately rather than relying on the guard as an error-handling mechanism.
Usage
Add the RoutesViaNotifiablePreferences trait to every notification that should respect preferences:
<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use SameOldNick\NotificationPreferences\Concerns\RoutesViaNotifiablePreferences; class MyNotification extends Notification { use RoutesViaNotifiablePreferences; // ... }
The trait provides via(). Do not also define via() on the notification, or it will take precedence and bypass preference routing.
Mapping a notification to a type
By default, notificationType() returns the notification's fully-qualified class name, which must exist as a key in notification-preferences.types. To use a shorter key instead, apply the NotificationType attribute to the class:
<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use SameOldNick\NotificationPreferences\Attributes\NotificationType; use SameOldNick\NotificationPreferences\Concerns\RoutesViaNotifiablePreferences; #[NotificationType('my-notification')] class MyNotification extends Notification { use RoutesViaNotifiablePreferences; public function toArray($notifiable): array { return ['message' => 'Hello!']; } }
The my-notification key matches the type defined in the Notification types section, so the notifiable's preferences for that type decide which channels this notification uses.
The attribute also accepts a backed enum, so one enum can own your type keys:
// app/Enums/NotificationType.php enum NotificationType: string { case Login = 'login'; case BackupFailed = 'backup_failed'; }
<?php namespace App\Notifications; use App\Enums\NotificationType; use Illuminate\Notifications\Notification; use SameOldNick\NotificationPreferences\Attributes\NotificationType as NotificationTypeAttribute; use SameOldNick\NotificationPreferences\Concerns\RoutesViaNotifiablePreferences; #[NotificationTypeAttribute(NotificationType::Login)] class LoginNotification extends Notification { use RoutesViaNotifiablePreferences; }
The enum case resolves to its backing value, so NotificationType::Login maps to the login type. Alias one of the two imports because both classes are named NotificationType.
The resolved value must match a key in notification-preferences.types.
Resolution order is the notification's own notificationType() method, then the attribute, then the class name, so overriding the method still wins. Attributes are not inherited, so place it on the concrete notification class rather than a base class.
Reading and updating preferences
The package does not ship routes or controllers. Resolve NotificationPreferencesService from the container and expose it through your own application:
use SameOldNick\NotificationPreferences\Services\NotificationPreferencesService; $service = app(NotificationPreferencesService::class); // Keyed by "{channel}:{type}", for example "mail:my-notification". $preferences = $service->getPreferencesForNotifiable($user); $service->updatePreferencesForNotifiable($user, [ 'my-notification' => [ 'channels' => [ 'mail' => false, 'database' => true, ], ], ]);
getPreferencesForNotifiable() returns type labels and categories, but only channel keys. To display channel names (for example, as column headings), resolve the catalog and call notificationChannels():
use SameOldNick\NotificationPreferences\Contracts\NotificationCatalog; $channels = app(NotificationCatalog::class)->notificationChannels(); // [ // 'mail' => ['label' => 'Email'], // 'database' => ['label' => 'In-app'], // ]
Channel labels may be translation keys, so pass them through __() before displaying them.
updatePreferencesForNotifiable() rejects types that are not available to the notifiable and channels that are not available for the submitted type, throwing an InvalidArgumentException before writing anything. Validate the request first so users get a 422 instead of a 500:
use SameOldNick\NotificationPreferences\Contracts\NotificationCatalog; use SameOldNick\NotificationPreferences\Services\NotificationPreferencesService; $catalog = app(NotificationCatalog::class); $service = app(NotificationPreferencesService::class); $allowedTypes = array_keys($service->getNotificationTypesForNotifiable($user));
getNotificationTypesForNotifiable() applies the same guards as getPreferencesForNotifiable(), so guarded-out types cannot be submitted either. A channel that is required for a type but not available is still accepted, because the type is deliverable through it.
Custom notification catalogs
NotificationCatalog is bound to the config-backed NotificationCatalogConfigProvider. To source types or channels from somewhere else — a database, a tenant, or a user's plan — bind your own implementation in a service provider:
<?php namespace App\Providers; use App\Support\DatabaseNotificationCatalog; use Illuminate\Support\ServiceProvider; use SameOldNick\NotificationPreferences\Contracts\NotificationCatalog; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(NotificationCatalog::class, DatabaseNotificationCatalog::class); } }
Both RoutesViaNotifiablePreferences and NotificationPreferencesService resolve the interface from the container, so replacing the binding changes routing and preferences together. Implement all six interface methods, return list<string> channel keys, and keep the singleton free of per-notifiable state — availableNotificationChannelsFor() and requiredNotificationChannelsFor() receive the notifiable for that reason.
To hide whole types from specific notifiables, also implement NotificationCatalogForNotifiable. It adds notificationTypesFor(object $notifiable): array, and catalogs that implement only NotificationCatalog are treated as unguarded. The config-backed provider implements it by running each type's guard.
To control the state used when a notifiable has no stored preference, implement NotificationChannelDefaults. It adds channelEnabledByDefault(string $notificationType, string $channel, object $notifiable): bool, which both the preferences list and delivery consult. Catalogs that do not implement it treat missing rows as enabled, and the config-backed provider reads enabled_by_default and default_channels.
Channels are already scoped to the notifiable through availableNotificationChannelsFor(). If you extend the config-backed provider, filter the parent list there:
public function availableNotificationChannelsFor(string $notificationType, object $notifiable): array { $channels = parent::availableNotificationChannelsFor($notificationType, $notifiable); return array_values(array_filter( $channels, fn (string $channel): bool => $channel !== 'sms' || $notifiable->phone_verified_at !== null, )); }
Required channels are appended even when they are not available, but a type the configured guard rejects resolves no channels at all, required ones included. Reject the type in the guard if it must never be delivered.
Upgrading
From 1.1.0 to 1.1.1
This release applies the notification type guard when channels are resolved and adds a hook for null notifiables. No database or configuration changes are required.
-
Audit guards for delivery.
via()now resolves no channels for a type the guard rejects, and required channels no longer override the guard. A guard that was only written for the preferences UI now also runs when a notification is sent, including from queue workers, so it must not rely on request-only state such as the session or the authenticated guard. Use the notifiable it receives, for example withGate::forUser($notifiable). -
Resolve
NotificationChannelResolverfrom the container. Its constructor now also requires aNotificationTypeGuardResolver.RoutesViaNotifiablePreferencesalready resolves it withapp(), so only code that instantiates the resolver directly must pass the guard resolver as well. -
Override
getNullNotifiableVia()only if needed. Notifications sent without a notifiable still resolve no channels by default. Override the method when they should use a fixed channel list.
From 1.0.x to 1.1.0
This release adds channel defaults and type guards, and makes available_channels optional. No database changes are required.
-
Merge the new configuration keys. The published file now documents
channels.*.enabled_by_default,types.*.default_channels, andguard. Existing published configs keep working unchanged: an omittedenabled_by_defaultstill means enabled, and an omittedguardleaves every type unguarded. Updating the package alone does not alter your channels — your published config wins.If you adopt the new
channelsarray, note that it shipsntfyas opt-in (enabled_by_default => false). Notifiables without a storedntfypreference will stop receiving it; set the flag totrueto keep the previous behaviour. -
Check
available_channelsagainstchannels. The key is now optional: when omitted, every channel registered inchannelsis offered, so you can delete the list entirely. If you keep it (globally or on a type), every value must be a key ofchannels; an unregistered channel now throws anInvalidArgumentExceptionas soon as the catalog resolves that list, such as when building the preferences payload or sending a notification. Add the missing channels tochannelswith alabel, or drop them fromavailable_channels. Required channels are unaffected, since they are never offered. -
Validate preference updates.
updatePreferencesForNotifiable()now rejects types and channels that are not available to the notifiable with anInvalidArgumentException, before writing anything. Validate the payload withgetNotificationTypesForNotifiable()andNotificationCatalog::availableNotificationChannelsFor()first, or catch the exception and map it to a422response. A submitted type may now also omitchannels, which writes nothing for that type. -
Audit channels you mark opt-in. Both the preferences list and delivery now consult
enabled_by_defaultanddefault_channelswhen a notifiable has no stored preference. A channel marked opt-in stops being delivered to existing users who never saved a preference for it. Channels without the flag keep the previous enabled behaviour, and required channels ignore defaults. -
Resolve
NotificationChannelResolverfrom the container. Its constructor now requires aNotificationCatalog.RoutesViaNotifiablePreferencesalready resolves it withapp(), so only code that instantiates the resolver directly must pass the catalog. -
Adopt the new extension points only if needed.
NotificationCatalogForNotifiable,NotificationChannelDefaults,NotificationTypeGuard, and theNotificationTypeattribute are additive; theNotificationCataloginterface itself is unchanged, so existing custom catalogs keep working. Configuringguardhides rejected types from the preferences list and from updates. From 1.1.1 it also blocks delivery, so a guarded-out type resolves no channels.
Laravel Boost
This package ships AI guidelines and an on-demand agent skill for Laravel Boost:
- Guidelines:
resources/boost/guidelines/core.blade.php - Skill:
resources/boost/skills/notification-preferences-development/SKILL.md
Both are installed automatically when an application runs php artisan boost:install (skills depend on the user selecting the skills feature). The skill also carries the upgrade checklist, so an assistant can reconcile configuration when the package version changes.
Development
composer install
composer test
composer lint
composer format
Security
Please review SECURITY.md for the vulnerability reporting policy.
License
This package is open-sourced software licensed under the MIT license.