Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Notification Log Laravel Package

spatie/laravel-notification-log

Logs all notifications sent by your Laravel app, storing them as NotificationLogItems so you can query what was sent to a user, display notification history, and make sending decisions (e.g., avoid duplicates) via helpers like wasSentTo() and inThePastMinutes().

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-notification-log
    

    Publish the migration:

    php artisan vendor:publish --provider="Spatie\NotificationLog\NotificationLogServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Enable Logging: Add the LogsNotifications trait to your User model (or any notifiable model):

    use Spatie\NotificationLog\LogsNotifications;
    
    class User extends Authenticatable
    {
        use LogsNotifications;
    }
    
  3. First Use Case: Send a notification and verify it’s logged:

    $user->notify(new InvoicePaid($invoice));
    

    Check the notification_logs table for the entry.


Where to Look First

  • Configuration: config/notification-log.php (default settings are minimal).
  • Migrations: database/migrations/[timestamp]_create_notification_logs_table.php (customize columns as needed).
  • Model Trait: LogsNotifications (understand how it hooks into Laravel’s notification system).

Implementation Patterns

Core Workflow

  1. Logging Notifications: The LogsNotifications trait automatically logs all notifications sent to the model. No manual intervention required for basic usage.

  2. Customizing Logged Data: Override the getNotificationLogData() method to include additional context:

    public function getNotificationLogData($notification)
    {
        return array_merge(parent::getNotificationLogData($notification), [
            'custom_field' => $this->customField,
        ]);
    }
    
  3. Querying Logs: Use the NotificationLog model to fetch logs:

    $logs = NotificationLog::forUser($user)->where('notifiable_type', 'App\Models\User')->get();
    
  4. Filtering by Notification Class: Logs include the notifiable_type and notification_type columns. Filter logs by notification class:

    $logs = NotificationLog::where('notification_type', 'App\Notifications\InvoicePaid')->get();
    

Integration Tips

  • Event-Based Logging: Listen to NotificationSent events for advanced logging logic:

    Notification::sending(function ($notifiable, $notification) {
        // Custom logic before logging
    });
    
  • Batch Processing: Use NotificationLog::query() with eager loading for performance:

    $logs = NotificationLog::with('notifiable')->get();
    
  • Soft Deletes: Enable soft deletes in the migration if needed:

    $table->softDeletes();
    
  • API Endpoints: Expose logs via an API route:

    Route::get('/logs', function () {
        return NotificationLog::latest()->take(100)->get();
    });
    

Gotchas and Tips

Pitfalls

  1. Missing Trait: Forgetting to add LogsNotifications to your model will result in no logs being recorded.

  2. Database Schema Changes: If you modify the notification_logs table after initial migration, run:

    php artisan migrate:fresh
    

    to avoid schema conflicts.

  3. Large Log Volumes: Unbounded logs can bloat your database. Implement retention policies (e.g., NotificationLog::where('created_at', '<', now()->subDays(30))->delete()).

  4. Notification Type Serialization: The notification_type column stores the fully qualified class name. Ensure your notification classes are autoloaded.


Debugging

  • Check Logs Table: Verify entries exist in notification_logs after sending notifications. Use:

    php artisan tinker
    NotificationLog::all();
    
  • Event Listeners: If logs aren’t appearing, check if NotificationSent events are firing:

    Notification::sending(function ($notifiable, $notification) {
        Log::debug('Notification sent:', ['notifiable' => $notifiable, 'notification' => $notification]);
    });
    
  • Model Binding: Ensure the notifiable_type and notifiable_id columns in notification_logs correctly reference your models.


Extension Points

  1. Custom Columns: Add columns to the notification_logs table and hydrate them in getNotificationLogData():

    public function getNotificationLogData($notification)
    {
        return [
            'ip_address' => request()->ip(),
            // ...
        ];
    }
    
  2. Observers: Use model observers to react to log creation:

    NotificationLog::observe(NotificationLogObserver::class);
    
  3. Policy Integration: Restrict access to logs via Gates/Policies:

    Gate::define('view-notification-logs', function ($user) {
        return $user->isAdmin();
    });
    
  4. Exporting Logs: Extend the package to support CSV/Excel exports:

    use Spatie\NotificationLog\NotificationLog;
    use Maatwebsite\Excel\Facades\Excel;
    
    Excel::download(new NotificationLogExport, 'notification-logs.xlsx');
    

Configuration Quirks

  • Default Guard: The package uses Laravel’s default auth guard. Override in config/notification-log.php if needed:

    'guard' => 'admin',
    
  • Log Retention: No built-in retention, but you can add a scheduled task:

    // app/Console/Kernel.php
    $schedule->command('notification-log:prune')->daily();
    

    Create a custom Artisan command to prune old logs.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport