PHP code example of sysmatter / laravel-notification-preferences

1. Go to this page and download the library: Download sysmatter/laravel-notification-preferences library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sysmatter / laravel-notification-preferences example snippets


return [
    // Define available channels
    'channels' => [
        'mail' => ['label' => 'Email', 'enabled' => true],
        'database' => ['label' => 'In-App', 'enabled' => true],
        'broadcast' => ['label' => 'Push', 'enabled' => true],
        'sms' => ['label' => 'SMS', 'enabled' => true],
    ],

    // Global default: 'opt_in' or 'opt_out'
    'default_preference' => 'opt_in',

    // Define notification groups
    'groups' => [
        'system' => [
            'label' => 'System Notifications',
            'description' => 'Important system updates',
            'default_preference' => 'opt_in',
            'order' => 1,
        ],
        'marketing' => [
            'label' => 'Marketing',
            'description' => 'Promotional content',
            'default_preference' => 'opt_out',
            'order' => 2,
        ],
    ],

    // Register your notifications
    'notifications' => [
        \App\Notifications\OrderShipped::class => [
            'group' => 'system',
            'label' => 'Order Shipped',
            'description' => 'Notification when your order ships',
            'default_preference' => 'opt_in',
            'default_channels' => ['mail', 'database'],
            'force_channels' => [], // Channels that can't be disabled
            'order' => 1,
        ],
        \App\Notifications\WeeklyNewsletter::class => [
            'group' => 'marketing',
            'label' => 'Weekly Newsletter',
            'description' => 'Our weekly email digest',
            'default_channels' => ['mail'],
            'order' => 2,
        ],
    ],
];

use SysMatter\NotificationPreferences\Concerns\HasNotificationPreferences;

class User extends Authenticatable
{
    use HasNotificationPreferences;
}

// This notification will automatically respect user preferences
$user->notify(new OrderShipped($order));

use SysMatter\NotificationPreferences\Concerns\ChecksNotificationPreferences;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification
{
    use ChecksNotificationPreferences;

    public function via($notifiable)
    {
        // Define all possible channels, preferences will filter them
        return $this->allowedChannels($notifiable, ['mail', 'database', 'broadcast']);
    }

    public function toMail($notifiable)
    {
        // ... 
    }
}

// Set a preference
$user->setNotificationPreference(
    OrderShipped::class,
    'mail',
    true // enabled
);

// Check a preference
$enabled = $user->getNotificationPreference(OrderShipped::class, 'mail');

// Get all preferences
$preferences = $user->getNotificationPreferences();

// Get structured table data for UI
$table = $user->getNotificationPreferencesTable();

$user->setGroupChannelPreference('marketing', 'mail', false);

$user->setGroupChannelPreference('system', 'database', true);

$user->setChannelPreferenceForAll('mail', false);

$user->setChannelPreferenceForAll('broadcast', true);

$user->setAllChannelsForNotification(OrderShipped::class, false);

$user->setAllChannelsForNotification(SecurityAlert::class, true);

$count = $user->setChannelPreferenceForAll('mail', false);
// Returns: 15 (updated 15 notification preferences)

$count = $user->setGroupChannelPreference('marketing', 'mail', false);

return response()->json([
    'message' => "Disabled email for {$count} marketing notifications"
]);

'notifications' => [
    SecurityAlert::class => [
        'group' => 'security',
        'label' => 'Security Alerts',
        'force_channels' => ['mail'], // Always send emails
    ],
],

// This will NOT disable email for SecurityAlert
$user->setChannelPreferenceForAll('mail', false);

public function disableAllEmails(Request $request)
{
    $count = $request->user()->setChannelPreferenceForAll('mail', false);
    
    return back()->with('success', "Disabled email notifications for {$count} notification types");
}

public function toggleMarketing(Request $request)
{
    $enabled = $request->boolean('enabled');
    $count = $request->user()->setGroupChannelPreference('marketing', 'mail', $enabled);
    
    $action = $enabled ? 'enabled' : 'disabled';
    
    return back()->with('success', "Marketing emails {$action}");
}

public function toggleNotificationType(Request $request, string $notificationType)
{
    $enabled = $request->boolean('enabled');
    $count = $request->user()->setAllChannelsForNotification($notificationType, $enabled);
    
    return response()->json([
        'updated' => $count,
        'enabled' => $enabled
    ]);
}

use SysMatter\NotificationPreferences\NotificationPreferenceManager;

$manager = app(NotificationPreferenceManager::class);

// Same methods available
$count = $manager->setGroupPreference($user, 'marketing', 'mail', false);
$count = $manager->setChannelPreference($user, 'mail', false);
$count = $manager->setNotificationPreference($user, OrderShipped::class, false);

public function index(Request $request)
{
    $user = $request->user();
    
    return view('preferences.notifications', [
        'preferences' => $user->getNotificationPreferencesTable(),
        'channels' => config('notification-preferences.channels'),
    ]);
}

public function update(Request $request)
{
    $user = $request->user();
    
    $validated = $request->validate([
        'action' => 'hannel'],
            $validated['enabled']
        ) ? 1 : 0,
        
        'group' => $user->setGroupChannelPreference(
            $validated['group'],
            $validated['channel'],
            $validated['enabled']
        ),
        
        'channel' => $user->setChannelPreferenceForAll(
            $validated['channel'],
            $validated['enabled']
        ),
        
        'notification' => $user->setAllChannelsForNotification(
            $validated['notification_type'],
            $validated['enabled']
        ),
    };
    
    return response()->json([
        'success' => true,
        'count' => $count,
    ]);
}

[
    [
        'group' => 'system',
        'label' => 'System Notifications',
        'description' => 'Important system updates',
        'notifications' => [
            [
                'type' => 'App\Notifications\OrderShipped',
                'label' => 'Order Shipped',
                'description' => 'Notification when your order ships',
                'channels' => [
                    'mail' => ['enabled' => true, 'forced' => false],
                    'database' => ['enabled' => true, 'forced' => false],
                    'broadcast' => ['enabled' => false, 'forced' => false],
                ],
            ],
        ],
    ],
    // ... more groups
]

use SysMatter\NotificationPreferences\NotificationPreferenceManager;

class NotificationPreferenceController extends Controller
{
    public function index(Request $request)
    {
        return inertia('Settings/Notifications', [
            'preferences' => $request->user()->getNotificationPreferencesTable(),
        ]);
    }

    public function update(Request $request, NotificationPreferenceManager $manager)
    {
        $validated = $request->validate([
            'notification_type' => '

Route::middleware(['auth'])->group(function () {
    Route::get('/settings/notifications', [NotificationPreferenceController::class, 'index']);
    Route::put('/settings/notifications', [NotificationPreferenceController::class, 'update']);
});

use SysMatter\NotificationPreferences\Models\NotificationPreference;
use App\Models\User;
use App\Notifications\OrderShipped;

it('filters channels based on user preferences', function () {
    $user = User::factory()->create();
    
    $user->setNotificationPreference(OrderShipped::class, 'mail', false);
    
    expect($user->getNotificationPreference(OrderShipped::class, 'mail'))
        ->toBeFalse();
});

it('returns structured table data', function () {
    $user = User::factory()->create();
    
    $table = $user->getNotificationPreferencesTable();
    
    expect($table)
        ->toBeArray()
        ->and($table[0])->toHaveKeys(['group', 'label', 'notifications'])
        ->and($table[0]['notifications'][0])->toHaveKeys(['type', 'label', 'channels']);
});

use SysMatter\NotificationPreferences\Models\NotificationPreference;
use App\Models\User;
use App\Notifications\OrderShipped;

it('filters channels based on user preferences', function () {
    $user = User::factory()->create();
    
    $user->setNotificationPreference(OrderShipped::class, 'mail', false);
    
    expect($user->getNotificationPreference(OrderShipped::class, 'mail'))
        ->toBeFalse();
});

'notifications' => [
    \App\Notifications\SecurityAlert::class => [
        'group' => 'system',
        'label' => 'Security Alerts',
        'force_channels' => ['mail', 'database'], // Can't be disabled
    ],
],

'notifications' => [
    \App\Notifications\OrderShipped::class => [
        'group' => 'system',
        'label' => 'Order Shipped',
        'default_channels' => ['mail', 'database'], // Only these enabled by default
    ],
],

use SysMatter\NotificationPreferences\NotificationPreferenceManager;

$manager = app(NotificationPreferenceManager::class);
$manager->clearUserCache($userId);
bash
php artisan vendor:publish --tag=notification-preferences-config
php artisan vendor:publish --tag=notification-preferences-migrations
bash
php artisan migrate