laravel-action-logger maintained by enadstack
Laravel Action Logger
A powerful, flexible, and developer-friendly Action Logger / Audit Log package for Laravel. Track all changes to your Eloquent models, support multi-tenancy out of the box, and optionally visualize logs with a beautiful Inertia + Vue 3 UI.
✨ Features
| Feature | Description |
|---|---|
| 🔍 Automatic CRUD Logging | Log created, updated, deleted, restored events automatically |
| 📝 Smart Diff Tracking | Only logs changed attributes on updates |
| 🏢 Multi-Tenant Ready | Column-based, request-based, or custom resolver |
| 🎯 Fluent API | Both direct method and fluent builder patterns |
| 🔎 Rich Query Scopes | Filter by subject, actor, event, date, tenant, and more |
| 🎨 Optional UI | Beautiful Inertia + Vue 3 + shadcn-vue dashboard |
| 🔧 Highly Configurable | Ignore attributes, models, events, and more |
| ⚡ Laravel 11 & 12 | Full compatibility with latest Laravel versions |
| 🧪 Fully Tested | 55+ automated tests |
📋 Requirements
| Requirement | Version |
|---|---|
| PHP | 8.2 or higher |
| Laravel | 11.0 or 12.0 |
🚀 Installation
Step 1: Install via Composer
composer require enadstack/laravel-action-logger
Step 2: Run the Install Command
php artisan action-logger:install
This will:
- ✅ Publish the configuration file
- ✅ Publish the migration
- ✅ Optionally run the migration
- ✅ Display next steps
Alternative: Manual Installation
# Publish config
php artisan vendor:publish --tag=action-logger-config
# Publish migration
php artisan vendor:publish --tag=action-logger-migrations
# Run migration
php artisan migrate
📖 Quick Start
1. Add the Trait to Your Models
use Enadstack\ActionLogger\Traits\HasActionLogs;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasActionLogs;
}
That's it! Now all CRUD operations are automatically logged:
// Logged: created
$post = Post::create(['title' => 'My First Post']);
// Logged: updated (only changed fields)
$post->update(['title' => 'Updated Title']);
// Logged: deleted
$post->delete();
2. Query the Logs
// Get all logs for a model
$logs = $post->actionLogs;
// Get the latest log
$latestLog = $post->latestActionLog();
// Get changes from an update
if ($latestLog->isUpdated()) {
foreach ($latestLog->getChanges() as $field => $change) {
echo "{$field}: {$change['old']} → {$change['new']}";
}
}
3. Log Custom Events
// Simple custom event
$post->logAction('published');
// With metadata
$post->logAction('shared', meta: [
'platform' => 'twitter',
'url' => 'https://...',
]);
📚 Documentation
| Document | Description |
|---|---|
| 📘 Usage Guide | ActionLogger service and facade usage |
| 📗 Trait Documentation | HasActionLogs trait complete guide |
| 📖 API Reference | Complete API documentation |
| 🔧 Commands | Artisan commands reference |
| 🎨 UI Guide | Optional Inertia + Vue UI setup |
| 📋 Quick Reference | Cheat sheet for common tasks |
| 🏢 Multi-Tenancy | Multi-tenant configuration guide |
| ⚙️ Configuration | Complete configuration reference |
| 🔄 Changelog | Version history |
🔧 Configuration
After installation, you can customize behavior in config/action-logger.php:
Enable/Disable Logging
// config/action-logger.php
'enabled' => env('ACTION_LOGGER_ENABLED', true),
Configure Events
'events' => [
'created',
'updated',
'deleted',
'restored',
],
Ignore Attributes
'ignore_attributes' => [
'updated_at',
'remember_token',
'password',
],
Multi-Tenancy
'tenant' => [
'mode' => 'column', // 'none', 'column', or 'resolver'
'column' => 'tenant_id',
],
🏢 Multi-Tenancy Support
The package supports three tenancy modes:
1. No Tenancy (Default)
'tenant' => [
'mode' => 'none',
],
2. Column-Based Tenancy
Automatically reads tenant ID from your models:
'tenant' => [
'mode' => 'column',
'column' => 'tenant_id', // or 'provider_id', 'organization_id', etc.
],
3. Custom Resolver
Use your own logic to determine tenant context:
'tenant' => [
'mode' => 'resolver',
'resolver' => \App\Services\MyTenantResolver::class,
],
See Multi-Tenancy Guide for complete documentation.
🎨 Optional UI
The package includes a beautiful Inertia + Vue 3 + shadcn-vue UI for viewing logs.
Enable the UI
# In .env
ACTION_LOGGER_UI_ENABLED=true
Publish UI Components (Optional)
php artisan vendor:publish --tag=action-logger-ui
Access the Dashboard
Visit /action-logs to see:
- 📊 Dashboard - Statistics and recent activity
- 📋 All Logs - Filterable, paginated log viewer
- 📦 Module Logs - Logs grouped by model type
- 🔍 Record Timeline - Complete history for any record
See UI Guide for full documentation.
🔎 Advanced Usage
Fluent API
use Enadstack\ActionLogger\Facades\ActionLogger;
ActionLogger::for($post)
->by($user)
->event('featured')
->withOld(['featured' => false])
->withNew(['featured' => true])
->addMeta('reason', 'Editor choice')
->save();
Custom Actor Resolution
class Order extends Model
{
use HasActionLogs;
protected function getActionLogActor(): ?object
{
return User::find($this->processed_by) ?? auth()->user();
}
}
Conditional Logging
class Comment extends Model
{
use HasActionLogs;
protected function shouldLogActionEvent(string $event): bool
{
return !$this->is_spam;
}
}
Rich Querying
use Enadstack\ActionLogger\Models\ActionLog;
// Combine multiple scopes
$logs = ActionLog::forSubject($post)
->forEvents(['created', 'updated'])
->recent(30)
->userActions()
->with('actor')
->latest()
->paginate(20);
// Track price changes
$priceHistory = $product->actionLogs()
->forEvent('updated')
->get()
->filter(fn($log) => $log->hasChangeFor('price'));
🔨 Maintenance
Prune Old Logs
# Remove logs older than 90 days
php artisan action-logger:prune --days=90
# Preview (dry run)
php artisan action-logger:prune --days=60 --dry-run
# Prune for specific tenant
php artisan action-logger:prune --tenant=1 --days=90
View Statistics
# Stats for last 30 days
php artisan action-logger:stats
# Stats for last 7 days
php artisan action-logger:stats --days=7
Schedule Automatic Pruning
// app/Console/Kernel.php
protected function schedule(Schedule $schedule): void
{
$schedule->command('action-logger:prune --days=90')
->weekly()
->sundays()
->at('02:00');
}
🧪 Testing
The package includes a comprehensive test suite:
# Run all tests
composer test
# Run with PHPUnit directly
vendor/bin/phpunit
# Run specific test suite
vendor/bin/phpunit --testsuite=Unit
vendor/bin/phpunit --testsuite=Feature
# Generate coverage report
vendor/bin/phpunit --coverage-html coverage
💡 Examples
Check out the example files in src/Examples/:
ExampleUsage.php- Service and facade usage examplesExampleHasActionLogs.php- Trait usage and customizationExampleCustomTenantResolver.php- Custom tenant resolver implementation
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
📄 License
The MIT License (MIT). Please see LICENSE for more information.