### Install Package via Composer
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/installation.md
Installs the humweb/notification-subscriptions package using Composer. This is the primary method for adding the package to your project.
```bash
composer require humweb/notification-subscriptions
```
--------------------------------
### Publish and Run Migrations
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/installation.md
Publishes the package's migration files and then runs them to create the necessary database tables (`notification_subscriptions` and `pending_notifications`).
```bash
php artisan vendor:publish --tag="notification-subscriptions-migrations"
php artisan migrate
```
--------------------------------
### Install Notification Subscriptions
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Installs the notification-subscriptions package using Composer. This is the primary step to integrate the package into your Laravel project.
```bash
composer require humweb/notification-subscriptions
```
--------------------------------
### Publish Configuration File
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/installation.md
Publishes the package's configuration file to your project's config directory, allowing for customization of settings.
```bash
php artisan vendor:publish --tag="notification-subscriptions-config"
```
--------------------------------
### Laravel Digest Notification Class Example
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/usage/digest-system.md
Provides a complete example of a Laravel Notification class (`UserNotificationDigest`) that handles the formatting and sending of digest notifications. It includes methods for sending via email (`toMail`) and as an array (`toArray`), along with constructor logic to accept the channel and pending notification data.
```php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Collection;
class UserNotificationDigest extends Notification implements ShouldQueue
{
use Queueable;
public string $channel;
public Collection $pendingNotificationsData;
public function __construct(string $channel, Collection $pendingNotificationsData)
{
$this->channel = $channel;
$this->pendingNotificationsData = $pendingNotificationsData;
}
public function via($notifiable): array
{
// Send the digest via the channel it was originally intended for
return [$this->channel];
}
public function toMail($notifiable): MailMessage
{
$mailMessage = (new MailMessage)
->subject('Your Notification Digest');
if ($this->pendingNotificationsData->isEmpty()) {
$mailMessage->line('You have no new notifications in this digest period.');
return $mailMessage;
}
$mailMessage->line('Here is a summary of your notifications:');
foreach ($this->pendingNotificationsData as $item) {
// Customize how each item in the digest is displayed
// $item['class'] is the original notification class
// $item['data'] contains the original constructor arguments for that notification
// $item['created_at'] is when the original notification was triggered
$mailMessage->line("---" ({$item['created_at']->format('M d, H:i')}) ---");
$mailMessage->line("Type: {$item['class']}"); // Example
// You might want to load $item['data'] into the original notification class
// and call a ->toDigestMail() method on it, or format data directly.
$dataString = implode(', ', array_map(fn($k, $v) => "$k: " . (is_object($v) || is_array($v) ? json_encode($v) : $v), array_keys($item['data']), $item['data']));
$mailMessage->line("Details: {$dataString}");
}
return $mailMessage;
}
public function toArray($notifiable): array
{
return [
'message' => 'You have new notifications in your digest.',
'count' => $this->pendingNotificationsData->count(),
'items' => $this->pendingNotificationsData->map(function ($item) {
return [
'original_class' => $item['class'],
'data' => $item['data'],
'triggered_at' => $item['created_at']->toIso8601String(),
];
})->all(),
];
}
}
```
--------------------------------
### Vue Component for Notification Settings UI
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/frontend-example.md
An example Inertia-Vue component for displaying and managing user notification settings. It uses the data passed from the controller to render forms for subscribing/unsubscribing and configuring digest intervals.
```html
getSubscribedChannels(string $type);
// Unsubscribe from all channels/digest settings for a type
$user->unsubscribeFromType(string $type);
// Unsubscribe from everything
$user->unsubscribeFromAll();
// Access Eloquent relation to get all NotificationSubscription models
$user->subscriptions;
```
--------------------------------
### Get Full Subscription Details
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Retrieves the complete details of a user's subscription for a given notification type and channel, including digest interval, time, day, and last sent time. Returns a NotificationSubscription model instance or null if not subscribed. Dependencies: User model with getSubscriptionDetails method.
```php
$details = $user->getSubscriptionDetails('comment:created', 'database');
if ($details) {
echo "Interval: " . $details->digest_interval;
echo "Time: " . $details->digest_at_time;
echo "Day: " . $details->digest_at_day;
echo "Last Digest Sent: " . $details->last_digest_sent_at;
}
```
--------------------------------
### Get Full Subscription Details
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/usage/subscribable-trait.md
Retrieves the full details of a user's subscription to a specific notification type and channel, including digest preferences and last sent time. Returns a NotificationSubscription model instance or null if not subscribed. Dependencies: User model with Subscribable trait, NotificationSubscription model.
```php
$details = $user->getSubscriptionDetails('comment:created', 'database');
if ($details) {
echo "Interval: " . $details->digest_interval;
echo "Time: " . $details->digest_at_time;
echo "Day: " . $details->digest_at_day;
echo "Last Digest Sent: " . $details->last_digest_sent_at;
}
```
--------------------------------
### Run Tests with Composer
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/testing.md
Executes the test suite using Composer's test script. This is the standard way to run tests.
```bash
composer test
```
--------------------------------
### Run Tests
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Commands to execute tests for the project using Composer and Pest. Includes an option to run tests with code coverage enabled via XDEBUG_MODE.
```bash
composer test
```
```bash
XDEBUG_MODE=coverage ./vendor/bin/pest --coverage
```
--------------------------------
### Publish and Run Migrations
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Publishes the package's migration files and then runs them to create the necessary database tables (`notification_subscriptions` and `pending_notifications`). These tables are essential for storing subscription data and pending digest notifications.
```bash
php artisan vendor:publish --tag="notification-subscriptions-migrations"
php artisan migrate
```
--------------------------------
### Laravel Controller for Notification Settings
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/frontend-example.md
Handles fetching user notification settings and available options, and processing updates. It interacts with a NotificationSubscriptions facade to retrieve subscribable types and digest intervals. Includes validation for incoming requests.
```php
mapWithKeys(function ($typeDetails, $typeKey) use ($user) {
$channels = collect($typeDetails['channels'] ?? [])->map(function ($channelConfig) use ($user, $typeKey) {
$subscription = $user ? $user->getSubscriptionDetails($typeKey, $channelConfig['name']) : null;
$digestAtTime = $subscription->digest_at_time ?? '09:00:00'; // Default with seconds
return [
'name' => $channelConfig['name'],
'label' => $channelConfig['label'],
'subscribed' => (bool) $subscription,
'digest_interval' => $subscription->digest_interval ?? 'immediate',
'digest_at_time' => $digestAtTime ? substr($digestAtTime, 0, 5) : '09:00', // HH:MM
'digest_at_day' => $subscription->digest_at_day ?? 'monday',
];
})->all();
return [$typeKey => [
'label' => $typeDetails['label'],
'description' => $typeDetails['description'],
'channels' => $channels,
]];
})->all();
return Inertia::render('Profile/NotificationSettings', [
'notificationSettings' => $notificationSettings,
'availableDigestIntervals' => $availableDigestIntervals,
'availableDaysOfWeek' => [
'monday' => 'Monday', 'tuesday' => 'Tuesday', 'wednesday' => 'Wednesday',
'thursday' => 'Thursday', 'friday' => 'Friday', 'saturday' => 'Saturday', 'sunday' => 'Sunday'
],
]);
}
public function store(Request $request)
{
$user = Auth::user();
$definedNotificationTypes = NotificationSettingsFacade::getSubscribableNotificationTypes();
$availableDigestIntervals = NotificationSettingsFacade::getDigestIntervals();
$validatedData = $request->validate([
'type' => ['required', 'string', Rule::in(array_keys($definedNotificationTypes))],
'channel' => ['required', 'string'],
'subscribed' => ['required', 'boolean'],
'digest_interval' => ['required', 'string', Rule::in(array_keys($availableDigestIntervals))],
'digest_at_time' => ['nullable', 'required_if:digest_interval,daily', 'required_if:digest_interval,weekly', 'date_format:H:i'],
'digest_at_day' => ['nullable', 'required_if:digest_interval,weekly', 'string', Rule::in(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])],
]);
$type = $validatedData['type'];
$channelName = $validatedData['channel'];
$isSubscribing = $validatedData['subscribed'];
$typeConfig = $definedNotificationTypes[$type] ?? null;
$allowedChannels = collect($typeConfig['channels'] ?? [])->pluck('name')->all();
if (! $typeConfig || ! in_array($channelName, $allowedChannels)) {
return back()->withErrors(['channel' => 'Invalid channel for the notification type.'])->withInput();
}
if ($isSubscribing) {
$user->subscribe(
$type,
$channelName,
$validatedData['digest_interval'],
$validatedData['digest_at_time'] ? $validatedData['digest_at_time'] . ':00' : null, // Append seconds
$validatedData['digest_at_day']
);
} else {
$user->unsubscribe($type, $channelName);
}
return back()->with('success', 'Notification settings updated.');
}
}
```
--------------------------------
### Run Tests with Coverage
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/testing.md
Executes the test suite using Pest with Xdebug coverage enabled. This command generates a code coverage report.
```bash
XDEBUG_MODE=coverage ./vendor/bin/pest --coverage
```
--------------------------------
### Key Configuration Options
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Defines the essential configuration parameters for the notification subscriptions package. These options control user models, database tables, digest intervals, and notification types.
```APIDOC
user_model: The class name of your User model.
subscription_model: The Eloquent model for storing subscriptions (defaults to `Humweb\Notifications\Models\NotificationSubscription`).
table_name: The database table for subscriptions (defaults to `notification_subscriptions`).
pending_notifications_table_name: Database table for storing notifications pending digest (defaults to `pending_notifications`).
digest_notification_class: The default Laravel Notification class to use for sending digests. It will receive the channel and a collection of pending notification data.
digest_intervals: An associative array defining the available digest periods users can select (e.g., `['immediate' => 'Immediate', 'daily' => 'Daily Digest']`). Keys are used internally, values are for display.
notifications: An array where each key is a unique string identifying a notification type (e.g., `app:updates`, `comment:created`).
label: A human-readable name for the notification.
description: A more detailed explanation.
class: (Optional) The FQCN of the corresponding Laravel Notification class. Useful for reference or dynamic dispatch.
channels: An array of available delivery channels. Each channel item should be an array with:
name: The technical identifier (e.g., 'mail', 'database').
label: A human-readable name for the UI.
```
--------------------------------
### Notification Channel Configuration
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/frontend-example.md
Vue.js template for configuring notification channel settings. It includes dropdowns for delivery intervals and inputs for specific times and days, dynamically shown based on the selected interval. The `updateSubscription` method is called on changes.
```html
No specific channels configured for this notification type.
```
--------------------------------
### Notification Class Preparation with Traits
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Demonstrates how to prepare custom Laravel Notification classes to integrate with the notification subscriptions package. It shows the use of `DispatchesNotifications` and `ChecksSubscription` traits for automatic dispatching and channel filtering based on user preferences.
```php
namespace App\\Notifications;
use Humweb\Notifications\Contracts\SubscribableNotification;
use Humweb\Notifications\Traits\ChecksSubscription;
use Humweb\Notifications\Traits\DispatchesNotifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
// use Illuminate\Contracts\Queue\ShouldQueue; // If you want to queue it
class NewComment extends Notification implements SubscribableNotification //, ShouldQueue
{
use Queueable, DispatchesNotifications, ChecksSubscription;
public $comment;
// Your notification constructor
public function __construct($comment)
{
$this->comment = $comment;
}
// Required by SubscribableNotification
// Must match a key in your config/notification-subscriptions.php 'notifications' array
public static function subscriptionType(): string
{
return 'comment:created';
}
// Standard Laravel Notification methods
// The via() method is supplied by ChecksSubscription trait.
// It will automatically filter channels based on immediate user subscriptions.
public function toMail($notifiable)
{
return (new \Illuminate\Notifications\Messages\MailMessage)
->line('A new comment was added on your post: ' . $this->comment->post_title)
->action('View Comment', url('/posts/' . $this->comment->post_id . '#comment-' . $this->comment->id))
->line('Thank you for using our application!');
}
public function toArray($notifiable)
{
return [
'comment_id' => $this->comment->id,
'comment_body' => $this->comment->body,
// ... other data
];
}
}
```
--------------------------------
### Publish Configuration File
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Publishes the package's configuration file to your Laravel project's config directory. This allows you to customize settings like the user model, table names, and notification types.
```bash
php artisan vendor:publish --tag="notification-subscriptions-config"
```
--------------------------------
### Manual Notification Dispatch Logic
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Outlines the manual steps required if not using Laravel's `DispatchesNotifications` trait. This involves identifying users, checking their subscriptions, sending immediately if applicable, or storing for digest processing. Dependencies: Manual implementation of subscription checking and storage logic.
```php
// 1. Identify users to notify.
// 2. For each user, check their subscription for the notification type and channel.
// 3. If "immediate", send it.
// 4. If "digest", store it in `pending_notifications` (see `Humweb\Notifications\Models\PendingNotification` model).
```
--------------------------------
### Create User Notification Digest Class
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/configuration.md
Defines the `UserNotificationDigest` class responsible for compiling and sending notification digests. It includes methods for specifying delivery channels (`via`), formatting for email (`toMail`), and providing array representation (`toArray`). The constructor accepts the channel and a collection of pending notification data.
```php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Collection;
class UserNotificationDigest extends Notification implements ShouldQueue
{
use Queueable;
public string $channel;
public Collection $pendingNotificationsData;
public function __construct(string $channel, Collection $pendingNotificationsData)
{
$this->channel = $channel;
$this->pendingNotificationsData = $pendingNotificationsData;
}
public function via($notifiable): array
{
// Send the digest via the channel it was originally intended for
return [$this->channel];
}
public function toMail($notifiable): MailMessage
{
$mailMessage = (new MailMessage)
->subject('Your Notification Digest');
if ($this->pendingNotificationsData->isEmpty()) {
$mailMessage->line('You have no new notifications in this digest period.');
return $mailMessage;
}
$mailMessage->line('Here is a summary of your notifications:');
foreach ($this->pendingNotificationsData as $item) {
// Customize how each item in the digest is displayed
// $item['class'] is the original notification class
// $item['data'] contains the original constructor arguments for that notification
// $item['created_at'] is when the original notification was triggered
$mailMessage->line("--- ({$item['created_at']->format('M d, H:i')}) ---");
$mailMessage->line("Type: {$item['class']}"); // Example
// You might want to load $item['data'] into the original notification class
// and call a ->toDigestMail() method on it, or format data directly.
$dataString = implode(', ', array_map(fn($k, $v) => "$k: " . (is_object($v) || is_array($v) ? json_encode($v) : $v), array_keys($item['data']), $item['data']));
$mailMessage->line("Details: {$dataString}");
}
return $mailMessage;
}
public function toArray($notifiable): array
{
return [
'message' => 'You have new notifications in your digest.',
'count' => $this->pendingNotificationsData->count(),
'items' => $this->pendingNotificationsData->map(function ($item) {
return [
'original_class' => $item['class'],
'data' => $item['data'],
'triggered_at' => $item['created_at']->toIso8601String(),
];
})->all(),
];
}
}
```
--------------------------------
### Inertia.js Route Configuration
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/frontend-example.md
This is a reminder to define the necessary route in your Laravel application's `routes/web.php` or `api.php` file. The route should point to the controller method responsible for handling the storage of notification settings.
```php
// Example in routes/web.php
use Illuminate\Support\Facades\Route;
Route::post('/profile/notification-settings', [YourController::class, 'store'])->name('profile.notification-settings.store');
```
--------------------------------
### Configure Notification Types
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Defines the available notification types, their labels, descriptions, associated Laravel notification classes (optional), and supported channels within the `config/notification-subscriptions.php` file. This configuration is crucial for enabling users to subscribe to specific events.
```php
\Humweb\Notifications\Database\Stubs\User::class, // Example, change to your User model
'subscription_model' => NotificationSubscription::class,
'table_name' => 'notification_subscriptions',
'pending_notifications_table_name' => 'pending_notifications', // Table for digest items
// Default notification class for digests
'digest_notification_class' => \Humweb\Notifications\Notifications\UserNotificationDigest::class,
// Available digest intervals for users to choose from
'digest_intervals' => [
'immediate' => 'Immediate',
'daily' => 'Daily Digest',
'weekly' => 'Weekly Digest',
],
'notifications' => [
'app:updates' => [
'label' => 'Application Updates',
'description' => 'Receive notifications about new features and important updates.',
'class' => App\Notifications\AppUpdatesNotification::class, // Optional: FQCN of your Laravel Notification
'channels' => [
['name' => 'mail', 'label' => 'Email'],
['name' => 'database', 'label' => 'Site Notification'],
]
],
'comment:created' => [
'label' => 'New Comments',
'description' => 'Get notified about new comments on your content.',
'class' => App\Notifications\NewComment::class, // Example
'channels' => [
['name' => 'mail', 'label' => 'Email'],
['name' => 'database', 'label' => 'Site Notification'],
]
],
// Add more notification types...
],
];
```
--------------------------------
### Configure Notification Subscriptions
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/configuration.md
Defines the notification types, their labels, descriptions, associated Laravel Notification classes, and available delivery channels within the `config/notification-subscriptions.php` file. This configuration is central to managing user notification preferences.
```php
\Humweb\Notifications\Database\Stubs\User::class, // Example, change to your User model
'subscription_model' => NotificationSubscription::class,
'table_name' => 'notification_subscriptions',
'pending_notifications_table_name' => 'pending_notifications', // Table for digest items
// Default notification class for digests
'digest_notification_class' => \Humweb\Notifications\Notifications\UserNotificationDigest::class,
// Available digest intervals for users to choose from
'digest_intervals' => [
'immediate' => 'Immediate',
'daily' => 'Daily Digest',
'weekly' => 'Weekly Digest',
],
'notifications' => [
'app:updates' => [
'label' => 'Application Updates',
'description' => 'Receive notifications about new features and important updates.',
'class' => App\Notifications\AppUpdatesNotification::class, // Optional: FQCN of your Laravel Notification
'channels' => [
['name' => 'mail', 'label' => 'Email'],
['name' => 'database', 'label' => 'Site Notification'],
]
],
'comment:created' => [
'label' => 'New Comments',
'description' => 'Get notified about new comments on your content.',
'class' => App\Notifications\NewComment::class, // Example
'channels' => [
['name' => 'mail', 'label' => 'Email'],
['name' => 'database', 'label' => 'Site Notification'],
]
],
// Add more notification types...
],
];
```
--------------------------------
### Create User Notification Digest Class
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Defines the `UserNotificationDigest` class responsible for formatting and sending digest notifications. It includes methods for specifying the delivery channel (`via`), formatting for email (`toMail`), and for array output (`toArray`). The constructor accepts the channel and a collection of pending notification data.
```php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Collection;
class UserNotificationDigest extends Notification implements ShouldQueue
{
use Queueable;
public string $channel;
public Collection $pendingNotificationsData;
public function __construct(string $channel, Collection $pendingNotificationsData)
{
$this->channel = $channel;
$this->pendingNotificationsData = $pendingNotificationsData;
}
public function via($notifiable): array
{
// Send the digest via the channel it was originally intended for
return [$this->channel];
}
public function toMail($notifiable): MailMessage
{
$mailMessage = (new MailMessage)
->subject('Your Notification Digest');
if ($this->pendingNotificationsData->isEmpty()) {
$mailMessage->line('You have no new notifications in this digest period.');
return $mailMessage;
}
$mailMessage->line('Here is a summary of your notifications:');
foreach ($this->pendingNotificationsData as $item) {
// Customize how each item in the digest is displayed
// $item['class'] is the original notification class
// $item['data'] contains the original constructor arguments for that notification
// $item['created_at'] is when the original notification was triggered
$mailMessage->line("--- ({$item['created_at']->format('M d, H:i')}) ---");
$mailMessage->line("Type: {$item['class']}"); // Example
// You might want to load $item['data'] into the original notification class
// and call a ->toDigestMail() method on it, or format data directly.
$dataString = implode(', ', array_map(fn($k, $v) => "$k: " . (is_object($v) || is_array($v) ? json_encode($v) : $v), array_keys($item['data']), $item['data']));
$mailMessage->line("Details: {$dataString}");
}
return $mailMessage;
}
public function toArray($notifiable): array
{
return [
'message' => 'You have new notifications in your digest.',
'count' => $this->pendingNotificationsData->count(),
'items' => $this->pendingNotificationsData->map(function ($item) {
return [
'original_class' => $item['class'],
'data' => $item['data'],
'triggered_at' => $item['created_at']->toIso8601String(),
];
})->all(),
];
}
}
```
--------------------------------
### Prepare Notification Class with Traits
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/configuration.md
Demonstrates how to use `DispatchesNotifications` and `ChecksSubscription` traits in a Laravel Notification class. The `DispatchesNotifications` trait adds a static `dispatch()` method for handling subscriptions and digests, while `ChecksSubscription` provides the `via()` method to filter channels based on immediate user subscriptions. The `SubscribableNotification` interface requires a `subscriptionType()` method to identify the notification.
```php
namespace App\Notifications;
use Humweb\Notifications\Contracts\SubscribableNotification;
use Humweb\Notifications\Traits\ChecksSubscription;
use Humweb\Notifications\Traits\DispatchesNotifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
// use Illuminate\Contracts\Queue\ShouldQueue; // If you want to queue it
class NewComment extends Notification implements SubscribableNotification //, ShouldQueue
{
use Queueable, DispatchesNotifications, ChecksSubscription;
public $comment;
// Your notification constructor
public function __construct($comment)
{
$this->comment = $comment;
}
// Required by SubscribableNotification
// Must match a key in your config/notification-subscriptions.php 'notifications' array
public static function subscriptionType(): string
{
return 'comment:created';
}
// Standard Laravel Notification methods
// The via() method is supplied by ChecksSubscription trait.
// It will automatically filter channels based on immediate user subscriptions.
public function toMail($notifiable)
{
return (new \Illuminate\Notifications\Messages\MailMessage)
->line('A new comment was added on your post: ' . $this->comment->post_title)
->action('View Comment', url('/posts/' . $this->comment->post_id . '#comment-' . $this->comment->id))
->line('Thank you for using our application!');
}
public function toArray($notifiable)
{
return [
'comment_id' => $this->comment->id,
'comment_body' => $this->comment->body,
// ... other data
];
}
}
```
--------------------------------
### Subscribable Trait API Reference
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/usage/subscribable-trait.md
API documentation for the Subscribable trait methods used for managing notification subscriptions.
```APIDOC
Subscribable Trait Methods:
subscribe(string $type, string $channel, string $digestInterval = 'immediate', ?string $digestAtTime = null, ?string $digestAtDay = null)
- Subscribes a user to a notification type and channel.
- Updates digest preferences if already subscribed.
- Parameters:
- type (string): The notification type key (e.g., 'comment:created').
- channel (string): The channel name (e.g., 'mail', 'database').
- digestInterval (string, optional): The digest preference ('immediate', 'daily', 'weekly'). Defaults to 'immediate'.
- digestAtTime (string|null, optional): The time of day for digests (HH:MM:SS or HH:MM).
- digestAtDay (string|null, optional): The day of the week for weekly digests ('monday', 'tuesday', etc.).
unsubscribe(string $type, string $channel)
- Unsubscribes a user from a specific notification type and channel.
- Parameters:
- type (string): The notification type key.
- channel (string): The channel name.
isSubscribedTo(string $type, string $channel): bool
- Checks if a user is subscribed to a notification type and channel.
- Returns: true if subscribed, false otherwise.
- Parameters:
- type (string): The notification type key.
- channel (string): The channel name.
getSubscriptionDetails(string $type, string $channel): ?NotificationSubscription
- Retrieves detailed subscription information, including digest preferences.
- Returns: A NotificationSubscription model instance or null.
- Parameters:
- type (string): The notification type key.
- channel (string): The channel name.
getSubscribedChannels(string $type): array
- Gets all subscribed channel names for a given notification type.
- Returns: An array of channel names.
- Parameters:
- type (string): The notification type key.
unsubscribeFromType(string $type)
- Unsubscribes from all channels and digest settings for a given notification type.
- Parameters:
- type (string): The notification type key.
unsubscribeFromAll()
- Unsubscribes the user from all notification types and channels.
subscriptions:
- Eloquent relationship to retrieve all NotificationSubscription models associated with the user.
NotificationSubscription Model Properties:
- type (string): The notification type.
- channel (string): The channel name.
- digest_interval (string): The digest interval ('immediate', 'daily', 'weekly').
- digest_at_time (string|null): The time of day for digests.
- digest_at_day (string|null): The day of the week for weekly digests.
- last_digest_sent_at (Carbon|null): The timestamp when the last digest was sent.
NotificationSubscriptions Facade Methods:
getSubscribableNotificationTypes(): array
- Retrieves a list of all configured subscribable notification types.
getDigestIntervals(): array
- Retrieves a list of configured digest intervals and their display names.
```
--------------------------------
### List Available Notification Types and Channels
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Retrieves lists of configured notification types and available digest intervals, useful for building user interfaces for notification preferences. Dependencies: Humweb\Notifications\Facades\NotificationSubscriptions facade.
```php
use Humweb\Notifications\Facades\NotificationSubscriptions;
$types = NotificationSubscriptions::getSubscribableNotificationTypes();
$availableDigestIntervals = NotificationSubscriptions::getDigestIntervals();
```
--------------------------------
### Dispatching a New Comment Notification
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/usage/dispatching-notifications.md
Demonstrates how to use the static `dispatch()` method from the `DispatchesNotifications` trait to send a notification. This method automatically checks user subscriptions and handles immediate or digest sending.
```php
use App\Notifications\NewComment;
$comment = // ... your comment model ...
$userToNotify = // ... the user who should receive this (if subscribed) ...
// This static dispatch method handles everything:
// - Checks if users are subscribed to 'comment:created'
// - If 'immediate' for a channel, sends via that channel (respecting via() from ChecksSubscription)
// - If 'daily' or 'weekly', stores it in 'pending_notifications' table for the digest command
NewComment::dispatch($comment);
```
--------------------------------
### Dispatch Notifications with Subscription Handling
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Dispatches notifications using Laravel's dispatch system, which automatically checks user subscriptions. It handles immediate sending for 'immediate' digests and queues notifications for 'daily' or 'weekly' digests. Requires Notification classes to use DispatchesNotifications and ChecksSubscription traits. Dependencies: Laravel's dispatch system, Notification classes with specific traits.
```php
use App\Notifications\NewComment;
$comment = // ... your comment model ...
$userToNotify = // ... the user who should receive this (if subscribed) ...
// This static dispatch method handles everything:
// - Checks if users are subscribed to 'comment:created'
// - If 'immediate' for a channel, sends via that channel (respecting via() from ChecksSubscription)
// - If 'daily' or 'weekly', stores it in 'pending_notifications' table for the digest command
NewComment::dispatch($comment);
```
--------------------------------
### Implementing SubscribableNotification Interface
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Explains the requirement to implement the `Humweb\Notifications\Contracts\SubscribableNotification` interface in custom notification classes. This interface mandates a static `subscriptionType()` method that links the notification to its configuration key.
```APIDOC
Implement the `Humweb\Notifications\Contracts\SubscribableNotification` interface, which requires a static `subscriptionType()` method. This method should return the string key that identifies this notification in your `notification-subscriptions.php` config file.
```
--------------------------------
### Laravel Controller for Notification Settings
Source: https://github.com/humweb/notification-subscriptions/blob/main/README.md
Handles fetching notification types, user subscriptions, and available digest intervals. It also processes requests to update user notification preferences.
```php
$typeDetails) {
$channels = [];
foreach ($typeDetails['channels'] as $channelConfig) {
$subscription = $user->getSubscriptionDetails($typeKey, $channelConfig['name']);
$channels[] = [
'name' => $channelConfig['name'],
'label' => $channelConfig['label'],
'subscribed' => (bool) $subscription,
'digest_interval' => $subscription->digest_interval ?? 'immediate',
'digest_at_time' => $subscription->digest_at_time ? substr($subscription->digest_at_time, 0, 5) : '09:00', // HH:MM
'digest_at_day' => $subscription->digest_at_day ?? 'monday',
];
}
$settings[$typeKey] = [
'label' => $typeDetails['label'],
'description' => $typeDetails['description'],
'channels' => $channels,
];
}
return Inertia::render('Profile/NotificationSettings', [
'notificationSettings' => $settings,
'availableDigestIntervals' => $availableDigestIntervals,
// Example days of the week
'availableDaysOfWeek' => [
'monday' => 'Monday', 'tuesday' => 'Tuesday', 'wednesday' => 'Wednesday',
'thursday' => 'Thursday', 'friday' => 'Friday', 'saturday' => 'Saturday', 'sunday' => 'Sunday'
],
]);
}
public function store(Request $request)
{
$request->validate([
'type' => 'required|string',
'channel' => 'required|string',
'subscribed' => 'required|boolean',
'digest_interval' => 'required|string|in:' . implode(',', array_keys(NotificationSettingsFacade::getDigestIntervals())),
'digest_at_time' => 'nullable|required_if:digest_interval,daily|required_if:digest_interval,weekly|date_format:H:i',
'digest_at_day' => 'nullable|required_if:digest_interval,weekly|string|in:monday,tuesday,wednesday,thursday,friday,saturday,sunday',
]);
$user = Auth::user();
if ($request->subscribed) {
$user->subscribe(
$request->type,
$request->channel,
$request->digest_interval,
$request->digest_at_time ? $request->digest_at_time . ':00' : null, // Append seconds
$request->digest_at_day
);
} else {
$user->unsubscribe($request->type, $request->channel);
}
return back()->with('success', 'Notification settings updated.');
}
}
```
--------------------------------
### Notification Settings Management
Source: https://github.com/humweb/notification-subscriptions/blob/main/docs/frontend-example.md
This Vue.js component allows users to manage their notification preferences. It dynamically renders notification types and channels, enabling users to subscribe or unsubscribe. It also displays flash messages for success or errors.
```Vue
Manage Your Notification Preferences
Choose which communications and channels you'd like to receive, and how often.