PHPackages                             csouza/notification-management - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. csouza/notification-management

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

csouza/notification-management
==============================

Laravel package for managing user notification preferences across multiple channels

v1.0.1(5mo ago)11MITPHPPHP ^8.1CI passing

Since Nov 21Pushed 5mo agoCompare

[ Source](https://github.com/csouza1995/notification-management)[ Packagist](https://packagist.org/packages/csouza/notification-management)[ Docs](https://github.com/csouza1995/notification-management)[ RSS](/packages/csouza-notification-management/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (3)Used By (0)

Laravel Notification Management
===============================

[](#laravel-notification-management)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1496afee3a8f6fcb15a3fc3bd5e929f38cbc1c99ff587675b5e7627f35fdd666/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63736f757a612f6e6f74696669636174696f6e2d6d616e6167656d656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/csouza/notification-management)[![Total Downloads](https://camo.githubusercontent.com/8043c3d37e8a8586862ebd3d2e1cd2cba9aad93ffdacc470ff654bbfcabd2d2e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63736f757a612f6e6f74696669636174696f6e2d6d616e6167656d656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/csouza/notification-management)[![GitHub Tests Action Status](https://camo.githubusercontent.com/00fe449a77725e3271e38f4acfa64595af5f9436215a81914d9e3a55e0f9e872/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63736f757a61313939352f6e6f74696669636174696f6e2d6d616e6167656d656e742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/csouza1995/notification-management/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/d3954fb283acac5c72e054a0e7210a12e4b2339ac0df31e97416ecfd61a5c7a7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63736f757a61313939352f6e6f74696669636174696f6e2d6d616e6167656d656e742f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/csouza1995/notification-management/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)

A powerful Laravel package that allows users to manage their notification preferences across multiple channels. Let your users decide how they want to be notified!

Features
--------

[](#features)

✨ **User Preferences**: Let users choose which channels they want to receive notifications through
📱 **Multiple Channels**: Support for Laravel native channels (mail, database, broadcast) and custom channels
🔧 **Easy Integration**: Simple trait to add to your User model
📊 **Notification Logging**: Track all sent notifications
🎯 **Type-based Control**: Different preferences per notification type
🚀 **API Ready**: Built-in REST API for managing preferences
🔐 **Built-in Notifications**: Includes `user.logged` notification out of the box

Installation
------------

[](#installation)

Install the package via composer:

```
composer require csouza/notification-management
```

Publish the config and migrations:

```
php artisan vendor:publish --tag=notification-management-config
php artisan vendor:publish --tag=notification-management-migrations
```

Run the migrations:

```
php artisan migrate
```

Configuration
-------------

[](#configuration)

Add the trait to your User model:

```
use Csouza\NotificationManagement\Traits\HasNotificationPreferences;

class User extends Authenticatable
{
    use HasNotificationPreferences;
}
```

Usage
-----

[](#usage)

### Managing User Preferences

[](#managing-user-preferences)

```
// Enable a channel for a notification type
$user->enableNotificationChannel('order.shipped', 'mail');
$user->enableNotificationChannel('order.shipped', 'database');

// Disable a channel
$user->disableNotificationChannel('order.shipped', 'sms');

// Check if user wants to receive via a channel
if ($user->wantsNotificationVia('order.shipped', 'mail')) {
    // User wants email notifications for shipped orders
}

// Get all active channels for a notification type
$channels = $user->getActiveChannelsFor('order.shipped');
// Returns: ['mail', 'database']

// Set bulk preferences
$user->setNotificationPreferences([
    'order.shipped' => ['mail' => true, 'sms' => false],
    'order.delivered' => ['mail' => true, 'database' => true],
]);
```

### Creating Notifications

[](#creating-notifications)

Use the `UsesNotificationPreferences` trait in your notification classes to automatically respect user preferences:

```
use Csouza\NotificationManagement\Traits\UsesNotificationPreferences;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class OrderShipped extends Notification
{
    use UsesNotificationPreferences;

    /**
     * Define the notification type identifier
     */
    protected string $notificationType = 'order.shipped';

    public function __construct(
        protected Order $order
    ) {}

    /**
     * No need to define via() - the trait handles it automatically
     * based on user preferences!
     */

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Your order has been shipped!')
            ->line('Your order #'.$this->order->id.' is on its way!')
            ->action('Track Order', url('/orders/'.$this->order->id));
    }

    public function toDatabase(object $notifiable): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => 'Your order has been shipped',
        ];
    }
}
```

The trait automatically:

- ✅ Checks user preferences for the notification type
- ✅ Returns only enabled channels
- ✅ Respects default configurations
- ✅ No need to manually implement the `via()` method!

**Advanced: Limiting Channels**

```
// Force specific channels (ignores user preferences)
class SecurityAlert extends Notification
{
    use UsesNotificationPreferences;

    protected string $notificationType = 'security.alert';
    protected array $forceChannels = ['database']; // Always use database
}

// Limit allowed channels (intersects with user preferences)
class MarketingEmail extends Notification
{
    use UsesNotificationPreferences;

    protected string $notificationType = 'marketing.promo';
    protected array $allowedChannels = ['mail']; // Only allow email, filter out others
}
```

### Sending Notifications

[](#sending-notifications)

The package integrates seamlessly with Laravel's notification system:

```
use App\Notifications\OrderShipped;
use Csouza\NotificationManagement\Facades\NotificationManager;

// Send notification respecting user preferences
NotificationManager::send($user, 'order.shipped', OrderShipped::class, [
    'order_id' => $order->id,
    'tracking_code' => $order->tracking_code,
]);

// Or using the notification instance
NotificationManager::send($user, 'order.shipped', new OrderShipped($order));

// Send by type (requires notification_types config)
NotificationManager::sendByType($user, 'order.shipped', [
    'order_id' => $order->id,
]);
```

### Automatic Event-to-Notification Mapping 🚀

[](#automatic-event-to-notification-mapping-)

**New!** Automatically send notifications when Laravel events are fired, without creating listener classes:

```
// config/notification-management.php
'event_notifications' => [
    // Simple: property extraction
    \Illuminate\Auth\Events\Login::class => [
        'notification_type' => 'user.logged',
        'notifiable' => 'user', // $event->user
    ],

    // Nested: dot notation
    \App\Events\OrderShipped::class => [
        'notification_type' => 'order.shipped',
        'notifiable' => 'order.user', // $event->order->user
        'data' => fn($event) => ['order_id' => $event->order->id],
    ],

    // Advanced: closure with condition
    \App\Events\PaymentFailed::class => [
        'notification_type' => 'payment.failed',
        'notifiable' => 'user',
        'condition' => fn($event) => $event->attempts >= 3,
    ],

    // Multiple: notify collection of users
    \App\Events\PostPublished::class => [
        'notification_type' => 'post.published',
        'notifiable' => fn($event) => $event->post->subscribers,
    ],
],
```

**Benefits:**

- ✅ No listener classes needed
- ✅ Configuration-driven
- ✅ Supports closures for complex logic
- ✅ Conditional notifications
- ✅ Multiple notifiables (collections)

See [Event Notifications Documentation](docs/event-notifications.md) for complete guide.

### Built-in User Login Notification

[](#built-in-user-login-notification)

The package includes a ready-to-use notification for user logins. Simply register the listener:

```
// app/Providers/EventServiceProvider.php
use Illuminate\Auth\Events\Login;
use Csouza\NotificationManagement\Listeners\SendUserLoggedNotification;

protected $listen = [
    Login::class => [
        SendUserLoggedNotification::class,
    ],
];
```

Now users will automatically receive notifications when they log in, including:

- IP Address
- Browser/User Agent
- Location (if configured)
- Login timestamp

Users can control how they receive these notifications:

```
// Enable email notifications for logins
$user->enableNotificationChannel('user.logged', 'mail');

// Disable SMS notifications for logins
$user->disableNotificationChannel('user.logged', 'sms');
```

See [docs/user-logged-notification.md](docs/user-logged-notification.md) for full documentation.

### Custom Channels

[](#custom-channels)

Register custom channels in your `AppServiceProvider`:

```
use Csouza\NotificationManagement\Managers\ChannelRegistry;

public function boot()
{
    $registry = app(ChannelRegistry::class);

    $registry->register('sms', \App\Channels\SmsChannel::class);
    $registry->register('telegram', \App\Channels\TelegramChannel::class);
    $registry->register('slack', \App\Channels\SlackChannel::class);
}
```

Or add them to `config/notification-management.php`:

```
'channels' => [
    'sms' => [
        'driver' => \App\Channels\SmsChannel::class,
        'enabled' => true,
        'description' => 'SMS notifications',
    ],
    'telegram' => [
        'driver' => \App\Channels\TelegramChannel::class,
        'enabled' => true,
        'description' => 'Telegram notifications',
    ],
],
```

### API Endpoints

[](#api-endpoints)

The package provides REST API endpoints for managing preferences:

```
GET    /api/notification-preferences          # Get all preferences
PUT    /api/notification-preferences          # Update preferences
POST   /api/notification-preferences/enable   # Enable a channel
POST   /api/notification-preferences/disable  # Disable a channel
GET    /api/notification-preferences/channels # Get available channels
GET    /api/notification-preferences/types    # Get notification types
GET    /api/notification-preferences/history  # Get notification history

```

**Example requests:**

```
// Enable a channel
POST /api/notification-preferences/enable
{
    "notification_type": "order.shipped",
    "channel": "mail"
}

// Bulk update preferences
PUT /api/notification-preferences
{
    "preferences": {
        "order.shipped": {
            "mail": true,
            "sms": false,
            "database": true
        },
        "order.delivered": {
            "mail": true,
            "database": true
        }
    }
}
```

### Notification History

[](#notification-history)

Track notification history for users:

```
// Get all notification history
$history = $user->getNotificationHistory();

// Get history for specific notification type
$history = $user->getNotificationHistory('order.shipped', 50);

// Via the manager
$history = NotificationManager::getNotificationHistory($user, 'order.shipped', 100);
```

Configuration Options
---------------------

[](#configuration-options)

Edit `config/notification-management.php`:

```
return [
    // Register custom channels
    'channels' => [
        // Your custom channels here
    ],

    // Routes configuration
    'routes' => [
        'enabled' => true,
        'middleware' => ['auth:sanctum'],
        'prefix' => 'api/notification-preferences',
    ],

    // Default settings
    'defaults' => [
        'enabled_channels' => ['mail', 'database'], // Default channels for new users
        'log_notifications' => true,                 // Enable logging
        'log_table' => 'notification_logs',
    ],

    // Define your notification types
    'notification_types' => [
        'order.created' => 'Order created',
        'order.shipped' => 'Order shipped',
        'order.delivered' => 'Order delivered',
        'user.mentioned' => 'You were mentioned',
    ],
];
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Carlos Souza](https://github.com/csouza1995)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance69

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

178d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a8f718bb3258b748d9751430cb0726d1fafb6f670b772ba4973778612417562a?d=identicon)[csouza1995](/maintainers/csouza1995)

---

Top Contributors

[![csouza1995](https://avatars.githubusercontent.com/u/51545352?v=4)](https://github.com/csouza1995 "csouza1995 (6 commits)")

---

Tags

laravelnotificationspreferenceschannelsuser-preferences

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/csouza-notification-management/health.svg)

```
[![Health](https://phpackages.com/badges/csouza-notification-management/health.svg)](https://phpackages.com/packages/csouza-notification-management)
```

###  Alternatives

[s-ichikawa/laravel-sendgrid-driver

This library adds a 'sendgrid' mail driver to Laravel.

4139.3M1](/packages/s-ichikawa-laravel-sendgrid-driver)[laravel-notification-channels/discord

Laravel notification driver for Discord.

2371.3M11](/packages/laravel-notification-channels-discord)[benwilkins/laravel-fcm-notification

Laravel FCM (Firebase Cloud Messaging) Notification Channel

210964.1k1](/packages/benwilkins-laravel-fcm-notification)[64robots/batch-notifications

A Laravel package that groups repetitive notifications in batches

142.4k](/packages/64robots-batch-notifications)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
