PHP code example of codinglabsau / laravel-notification-subscriptions

1. Go to this page and download the library: Download codinglabsau/laravel-notification-subscriptions 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/ */

    

codinglabsau / laravel-notification-subscriptions example snippets


// app/Enums/NotificationChannel.php
namespace App\Enums;

use Codinglabs\NotificationSubscriptions\Contracts\SubscribableChannel;

enum NotificationChannel: string implements SubscribableChannel
{
    case DATABASE = 'database';
    case MAIL = 'mail';
    case SLACK = 'slack';

    public function driver(): string
    {
        return $this->value;
    }

    public function label(): string
    {
        return match ($this) {
            self::DATABASE => 'In-App',
            self::MAIL => 'Email',
            self::SLACK => 'Slack',
        };
    }

    public function isEnabled(): bool
    {
        return true;
    }

    public function defaultOn(): bool
    {
        return match ($this) {
            self::SLACK => false,
            default => true,
        };
    }

    public function hasRateLimiting(): bool
    {
        return match ($this) {
            self::DATABASE => false,
            default => true,
        };
    }

    public function rateLimitDuration(): int
    {
        return match ($this) {
            self::MAIL => 300, // 5 minutes
            default => 60,
        };
    }
}

use Codinglabs\NotificationSubscriptions\Concerns\HasNotificationSubscriptions;

class User extends Authenticatable
{
    use HasNotificationSubscriptions;

    // ...
}

use Codinglabs\NotificationSubscriptions\Facades\NotificationSubscriptions;

public function boot(): void
{
    NotificationSubscriptions::register([
        \App\Notifications\OrderShippedNotification::class,
        \App\Notifications\NewMessageNotification::class,
    ]);

    // Conditional registration
    if (config('features.slack_enabled')) {
        NotificationSubscriptions::register([
            \App\Notifications\SlackAlertNotification::class,
        ]);
    }
}

return [
    // ...
    App\Providers\NotificationSubscriptionsServiceProvider::class,
];

use App\Enums\NotificationChannel;
use Illuminate\Notifications\Notification;
use Codinglabs\NotificationSubscriptions\Concerns\DispatchesNotifications;
use Codinglabs\NotificationSubscriptions\Contracts\SubscribableNotification;

class OrderShippedNotification extends Notification implements SubscribableNotification
{
    use DispatchesNotifications;

    public function __construct(
        public Order $order
    ) {}

    // Unique identifier for this notification type
    public static function type(): string
    {
        return 'order_shipped';
    }

    // Which channels this notification supports
    public static function channels(): array
    {
        return [NotificationChannel::DATABASE, NotificationChannel::MAIL];
    }

    // Who should receive this notification
    public function subscribers()
    {
        return collect([$this->order->user]);
    }

    // Standard Laravel notification methods
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject('Your order has shipped!')
            ->line("Order #{$this->order->id} is on its way.");
    }

    public function toArray($notifiable)
    {
        return [
            'title' => 'Order Shipped',
            'message' => "Order #{$this->order->id} has shipped.",
            'order_id' => $this->order->id,
        ];
    }
}

// This automatically:
// 1. Finds all subscribers
// 2. Checks each user's channel preferences
// 3. Applies rate limiting
// 4. Sends to appropriate channels only

OrderShippedNotification::sendToSubscribers($order);

// Subscribable - respects user preferences
OrderShippedNotification::sendToSubscribers($order);

// Transactional - always sends (standard Laravel)
$user->notify(new PasswordResetNotification());

use NotificationChannels\OneSignal\OneSignalChannel;

enum NotificationChannel: string implements SubscribableChannel
{
    case DATABASE = 'database';
    case MAIL = 'mail';
    case PUSH = OneSignalChannel::class;
    case SLACK = 'slack';

    public function driver(): string
    {
        return $this->value;
    }

    public function label(): string
    {
        return match ($this) {
            self::DATABASE => 'In-App',
            self::MAIL => 'Email',
            self::PUSH => 'Push Notifications',
            self::SLACK => 'Slack',
        };
    }

    public function isEnabled(): bool
    {
        return match ($this) {
            self::PUSH => config('services.onesignal.app_id') !== null,
            self::SLACK => config('services.slack.webhook_url') !== null,
            default => true,
        };
    }

    public function defaultOn(): bool
    {
        return match ($this) {
            self::PUSH, self::SLACK => false,
            default => true,
        };
    }

    public function hasRateLimiting(): bool
    {
        return match ($this) {
            self::DATABASE => false, // In-app doesn't need rate limiting
            default => true,
        };
    }

    public function rateLimitDuration(): int
    {
        return match ($this) {
            self::MAIL => 300,  // 5 minutes for emails
            self::PUSH => 60,   // 1 minute for push
            self::SLACK => 60,  // 1 minute for Slack
            default => config('notification-subscriptions.default_rate_limit_duration', 60),
        };
    }
}

public function subject(): ?Model
{
    return $this->order;  // The model triggering the notification
}

class TicketReplyNotification extends Notification implements SubscribableNotification
{
    use DispatchesNotifications;

    public static function type(): string
    {
        return 'ticket_reply';
    }

    public static function channels(): array
    {
        return [NotificationChannel::DATABASE, NotificationChannel::MAIL, NotificationChannel::PUSH];
    }

    // Mail is mandatory — users cannot unsubscribe from it
    public static function mandatoryChannels(): array
    {
        return [NotificationChannel::MAIL];
    }

    // ...
}

NotificationPreferences {
    types: [...],
    values: [...],
    mandatory: [
        'ticket_reply' => ['mail'],
    ],
}

use Codinglabs\NotificationSubscriptions\Concerns\ValidatesNotificationPreferences;

class NotificationSettingsController extends Controller
{
    public function edit()
    {
        return view('settings.notifications', [
            'preferences' => auth()->user()->getNotificationPreferences(),
        ]);
    }

    public function update(UpdateNotificationSettingsRequest $request)
    {
        auth()->user()->updateNotificationPreferences($request->validated());

        return redirect()->back()->with('success', 'Preferences saved.');
    }
}

// Form request - just add the trait, no configuration needed
class UpdateNotificationSettingsRequest extends FormRequest
{
    use ValidatesNotificationPreferences;
}

NotificationPreferences {
    // Channel options for the UI (enabled channels only)
    types: [
        'order_shipped' => ['database' => 'In-App', 'mail' => 'Email', 'slack' => 'Slack'],
        'new_message' => ['mail' => 'Email'],
    ],
    // User's current selections (or defaults)
    values: [
        'order_shipped' => ['database', 'mail'],
        'new_message' => ['mail', 'slack'],
    ],
    // Channels that cannot be unsubscribed from
    mandatory: [
        'order_shipped' => ['mail'],
    ],
}

class OrderShippedNotification extends Notification implements SubscribableNotification
{
    use DispatchesNotifications;

    public static function type(): string
    {
        return 'order_shipped';
    }

    // Custom methods for UI (not part of interface)
    public static function label(): string
    {
        return 'Order Shipping Updates';
    }

    public static function description(): string
    {
        return 'Get notified when your orders ship and are delivered.';
    }

    // ...
}

class OrderShippedNotification extends Notification implements SubscribableNotification
{
    use DispatchesNotifications;

    public static function beforeSend($notification): void
    {
        // Log, track analytics, modify notification, etc.
        Log::info('Sending order shipped notification', [
            'order_id' => $notification->order->id,
        ]);
    }

    // ...
}

// app/Models/NotificationSubscription.php
use Codinglabs\NotificationSubscriptions\Models\NotificationSubscription as BaseModel;

class NotificationSubscription extends BaseModel
{
    // Add custom methods, scopes, etc.
}

// config/notification-subscriptions.php
'subscription_model' => App\Models\NotificationSubscription::class,
bash
php artisan vendor:publish --tag="laravel-notification-subscriptions-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-notification-subscriptions-config"
bash
php artisan vendor:publish --tag="laravel-notification-subscriptions-provider"
blade
<form method="POST" action="{{ route('settings.notifications.update') }}">
    @csrf
    @method('PUT')

    @foreach($preferences->types as $notificationType => $channels)
        <div class="notification-group">
            <h3>{{ Str::title(str_replace('_', ' ', $notificationType)) }}</h3>

            @foreach($channels as $channel => $label)
                <label>
                    <input
                        type="checkbox"
                        name="{{ $notificationType }}[]"
                        value="{{ $channel }}"
                        @checked(in_array($channel, $preferences->values[$notificationType] ?? []))
                    />
                    {{ $label }}
                </label>
            @endforeach
        </div>
    @endforeach

    <button type="submit">Save Preferences</button>
</form>