Laravel Notification Log

repository·main·Indexed 42 days ago

https://github.com/spatie/laravel-notification-log

A package for logging all notifications sent by a Laravel application. It allows developers to track notification history, implement rate-limiting via wasSentTo(), and query logs using the NotificationLogItem model or the HasNotifiableHistory trait.

Tokens
6.9K
Snippets
29
Records
35
Agent score
51%

What's inside Laravel Notification Log

  1. Log notifications sent by your Laravel app

    main
    The spatie/laravel-notification-log package automatically logs all notifications sent by your Laravel application. This enables you to track notification history and implement logic based on whether specific notifications have been sent to users in the past.
  2. Add extra information to logged notifications

    main

    The notification_log_items table includes a JSON column named extra for storing custom metadata.

    To populate this column, implement a logExtra method within your Notification class. This method must accept an Illuminate\Notifications\Events\NotificationSending event as its argument and return an array of data. This array will be automatically stored in the extra column when the notification is logged.

    use Illuminate\Notifications\Events\NotificationSending;
    
    // in a notification
    public function logExtra(NotificationSending $event): array
    {
        return ['extraKey' => 'extraValue'];
    }
  3. Use a custom notification log model

    main

    You can use a custom model instead of the default NotificationLogItem to customize behaviors such as the database connection or pruning strategies.

    To implement this:

    1. Create a new class that extends Spatie\NotificationLog\Models\NotificationLogItem.
    2. Update your notification-log configuration file to point to your new class using the model key.
    // 1. Create your custom model
    use Spatie\NotificationLog\Models\NotificationLogItem;
    
    class CustomLogItem extends NotificationLogItem
    {
        // Add custom properties or methods here
    }
    
    // 2. Register it in config/notification-log.php
    return [
        'model' => CustomLogItem::class,
        // ...
    ];
  4. Customize the notification type logged in the database

    main

    By default, the package saves the fully qualified class name of a notification into the notification_type column of the notification_log_items table.

    To use a custom string instead of the class name, implement a logType() method within your notification class. This method must return a string representing the value you want to be stored in the database.

    // in a notification
    
    public function logType(): string
    {
        return 'customType';
    }
  5. Add a fingerprint to a notification

    main

    By default, notifications are logged based on their constructor parameters. To provide a custom, human-readable, or specific identifier for a notification in the logs, add a fingerprint() method to your notification class. This method should return a string. This string will be stored in the fingerprint column of the NotificationLogItem model.

    use Illuminate\Notifications\Notification;
    
    class OrderSentNotification extends Notification
    {
        public function __construct(
            public Order $order,
        ) {}
        
        public function fingerprint()
        {
            return "order-\{$this->order->id}";
        }
    }
  6. Use the HasHistory trait to prevent duplicate notifications

    main

    By including the Spatie\NotificationLog\Models\Concerns\HasHistory trait in your Notification class, you gain access to methods that allow you to inspect the notification's history. This is useful for implementing rate-limiting or conditional sending logic within the shouldSend() method.

    For example, you can use wasSentTo($notifiable)->inThePastMinutes(60) to ensure a notification is only sent if it hasn't been sent to that specific user in the last 60 minutes.

    use Spatie\NotificationLog\Models\Concerns\HasHistory;
    
    // in a notification
    class MyNotification extends Notification
    {
        use HasHistory;
    
        // verifying if the queued notification can be sent based in the history
        public function shouldSend($notifiable)
        {
              return ! $this
                ->wasSentTo($notifiable)
                ->inThePastMinutes(60);
        }
    }
  7. Search logged notifications using the HasNotifiableHistory trait

    main

    To search for logged notifications directly through a model (e.g., a User), use the Spatie\NotificationLog\Models\Concerns\HasNotifiableHistory trait.

    This adds two main capabilities:

    1. notificationLogItems: A MorphMany relationship to all logged notifications for that model.
    2. latestLoggedNotification(): A method to retrieve the single most recent log item, supporting the same restriction parameters as NotificationLogItem::latestFor().
    use Illuminate\Database\Eloquent\Model;
    use Spatie\NotificationLog\Models\Concerns\HasNotifiableHistory;
    use Spatie\NotificationLog\Notifications\Notifiable;
    
    class User extends Model
    {
        use Notifiable;
        use HasNotifiableHistory;
    }
    
    // Accessing the relationship
    $loggedNotifications = $user->notificationLogItems;
    $recentFive = $user->notificationLogItems()->limit(5)->get();
    
    // Accessing the latest notification with restrictions
    $logItem = $user->latestLoggedNotification(
        notificationType: OrderSentNotification::class,
        before: $carbon,
        after: $carbon,
        fingerprint: 'dummy-fingerprint'
    );
  8. Handle Laravel on-demand notifications

    main

    When using Laravel's On Demand Notifications feature (sending notifications to addresses not backed by a specific model), the laravel-notification-log package handles them by setting both notifiable_id and notifiable_type to null in the notification_log_items table.

    To configure how these anonymous notifications are handled, use the anonymous_notifiable_properties property in your configuration.

    Notification::route('mail', 'taylor@example.com')
        ->notify(new InvoicePaidNotification($invoice));