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().
Installation:
composer require spatie/laravel-notification-log
Publish the migration:
php artisan vendor:publish --provider="Spatie\NotificationLog\NotificationLogServiceProvider" --tag="migrations"
php artisan migrate
Enable Logging:
Add the LogsNotifications trait to your User model (or any notifiable model):
use Spatie\NotificationLog\LogsNotifications;
class User extends Authenticatable
{
use LogsNotifications;
}
First Use Case: Send a notification and verify it’s logged:
$user->notify(new InvoicePaid($invoice));
Check the notification_logs table for the entry.
config/notification-log.php (default settings are minimal).database/migrations/[timestamp]_create_notification_logs_table.php (customize columns as needed).LogsNotifications (understand how it hooks into Laravel’s notification system).Logging Notifications:
The LogsNotifications trait automatically logs all notifications sent to the model. No manual intervention required for basic usage.
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,
]);
}
Querying Logs:
Use the NotificationLog model to fetch logs:
$logs = NotificationLog::forUser($user)->where('notifiable_type', 'App\Models\User')->get();
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();
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();
});
Missing Trait:
Forgetting to add LogsNotifications to your model will result in no logs being recorded.
Database Schema Changes:
If you modify the notification_logs table after initial migration, run:
php artisan migrate:fresh
to avoid schema conflicts.
Large Log Volumes:
Unbounded logs can bloat your database. Implement retention policies (e.g., NotificationLog::where('created_at', '<', now()->subDays(30))->delete()).
Notification Type Serialization:
The notification_type column stores the fully qualified class name. Ensure your notification classes are autoloaded.
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.
Custom Columns:
Add columns to the notification_logs table and hydrate them in getNotificationLogData():
public function getNotificationLogData($notification)
{
return [
'ip_address' => request()->ip(),
// ...
];
}
Observers: Use model observers to react to log creation:
NotificationLog::observe(NotificationLogObserver::class);
Policy Integration: Restrict access to logs via Gates/Policies:
Gate::define('view-notification-logs', function ($user) {
return $user->isAdmin();
});
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');
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.
How can I help you explore Laravel packages today?