codersandip/laravel-audit-pro
最新稳定版本:v1.0.0
Composer 安装命令:
composer require codersandip/laravel-audit-pro
包简介
An advanced activity and audit logging system for Laravel applications with admin UI, export, and queue support.
README 文档
README
An advanced activity and audit logging system for Laravel 9–12.
Track every model change, capture rich request metadata, and browse logs through a beautiful dark-themed admin panel — all with zero configuration needed to get started.
✨ Features
| Feature | Description |
|---|---|
| 🔍 Model Tracking | Auto-detect create / update / delete / restore events |
| 📊 Before & After Diff | Store changed fields only — clean JSON diffs |
| 👤 User Tracking | Auth user ID, name, email (multi-guard support) |
| 🌐 Request Metadata | IP address, device type, browser, OS |
| 🎨 Admin Panel UI | Beautiful dark Bootstrap 5 UI with search, filters, pagination |
| 📤 CSV Export | Date-range and filter-based CSV export |
| ⚡ Queue Support | Optional async logging via Laravel Queues |
| 🔒 Security | Middleware protection, configurable prefix |
| 🧹 Log Retention | Configurable pruning via Artisan command |
| 📦 Publishable | Config, migrations, views, and assets |
📋 Requirements
- PHP 8.2+
- Laravel 9.x / 10.x / 11.x / 12.x
jenssegers/agent(for device/browser detection — installed automatically)
🚀 Installation
Step 1 — Require the package
composer require codersandip/laravel-audit-pro
Laravel 9+ auto-discovers the service provider via
extra.laravelincomposer.json.
No manual provider registration needed.
Step 2 — Publish the config
php artisan vendor:publish --tag=audit-pro-config
This publishes config/audit-pro.php to your application.
Step 3 — Publish & run migrations
php artisan vendor:publish --tag=audit-pro-migrations php artisan migrate
Or run the migration directly without publishing:
php artisan migrate
Step 4 — (Optional) Publish views & assets
# Customise the Blade views php artisan vendor:publish --tag=audit-pro-views # Publish static assets to public/vendor/audit-pro php artisan vendor:publish --tag=audit-pro-assets
⚙️ Configuration
All options live in config/audit-pro.php (after publishing).
Key settings:
// Enable / disable globally 'enabled' => env('AUDIT_PRO_ENABLED', true), // Separate DB connection (optional) 'connection' => env('AUDIT_PRO_CONNECTION', null), // Models automatically observed (alternative to HasActivityLog trait) 'observe_models' => [ \App\Models\User::class, \App\Models\Order::class, ], // Events to track 'events' => ['created', 'updated', 'deleted', 'restored'], // Fields NEVER included in diffs 'exclude_fields' => ['password', 'remember_token', 'updated_at', 'created_at'], // Async queue logging 'queue' => [ 'enabled' => env('AUDIT_PRO_QUEUE', false), 'name' => env('AUDIT_PRO_QUEUE_NAME', 'audit-pro'), ], // Admin panel route configuration 'routes' => [ 'enabled' => true, 'prefix' => env('AUDIT_PRO_ROUTE_PREFIX', 'audit-pro'), 'middleware' => ['web', 'auth'], ], // Auto-delete logs older than N days (null = keep forever) 'retention_days' => env('AUDIT_PRO_RETENTION', null),
📖 Usage
Option A — HasActivityLog Trait (Per-model)
Add the trait to any Eloquent model:
use Codersandip\AuditPro\Traits\HasActivityLog; class Order extends Model { use HasActivityLog; // Optional — exclude specific fields from diffs protected array $auditExclude = ['secret_token']; // Optional — only track these fields (whitelist) protected array $auditInclude = ['status', 'total', 'paid_at']; // Optional — custom log description public function getActivityLogDescription(string $event): ?string { return "Order #{$this->id} was {$event}"; } }
That's it! Every create, update, delete, and restore will be logged automatically.
Option B — Global Observer (Config-based)
Add models to config/audit-pro.php instead of adding the trait:
'observe_models' => [ \App\Models\Product::class, \App\Models\User::class, ],
Manual Logging
Use the AuditPro Facade or the audit_log() helper:
use Codersandip\AuditPro\Facades\AuditPro; // Facade AuditPro::log( event: 'payment', subject: $order, oldValues: ['status' => 'pending'], newValues: ['status' => 'paid'], description: 'Payment processed via Stripe', extra: ['stripe_charge_id' => 'ch_xxx'], ); // Helper function audit_log('exported', $report, description: 'Admin exported monthly report');
Batch Logging
Group related events under one UUID for traceability:
audit_batch(function () use ($order, $invoice) { $order->update(['status' => 'paid']); $invoice->update(['paid_at' => now()]); });
Or via Facade:
$batchId = AuditPro::startBatch(); $order->update(['status' => 'shipped']); $shipment->create([...]); AuditPro::endBatch();
Skip Auditing Temporarily
// Single callback Order::withoutAuditing(function () { Order::where('status', 'old')->update(['status' => 'archived']); }); // Toggle manually Order::disableAuditing(); // … bulk operations … Order::enableAuditing();
Retrieve Logs for a Model
// Via trait method $logs = $order->activityLogs(); // Via helper $logs = audit_logs_for($order); // Via query scopes use Codersandip\AuditPro\Models\ActivityLog; ActivityLog::forSubject(Order::class, $orderId) ->event('updated') ->dateRange('2024-01-01', '2024-01-31') ->latest() ->get();
🖥️ Admin Panel
Visit the panel at:
http://yourdomain.test/audit-pro
Features:
- Stat cards — total, created, updated, deleted, today's count
- Filters — search, model, event, user, date range
- Paginated table with before/after diff modal
- CSV export respecting active filters
Protecting the Panel
The panel uses the middleware configured in audit-pro.routes.middleware (default: ['web', 'auth']).
To require a specific role/permission, update:
// config/audit-pro.php 'routes' => [ 'middleware' => ['web', 'auth', 'can:view-audit-logs'], ],
🔒 Disable Logging for Specific Routes
Use the built-in middleware:
// routes/web.php Route::middleware('audit-pro.disable')->group(function () { Route::post('/bulk-import', BulkImportController::class); });
📤 Export
Via Admin Panel UI
Click the Export CSV button on the logs listing page. Active filters are included in the export.
Via Artisan
# Export all logs php artisan audit-pro:export # Export last 7 days of deleted events php artisan audit-pro:export --days=7 --event=deleted # Custom output path php artisan audit-pro:export --path=/var/backups/audit
🧹 Log Retention
# Delete logs older than config retention_days value php artisan audit-pro:clean # Override days at runtime php artisan audit-pro:clean --days=30
Schedule in app/Console/Kernel.php:
$schedule->command('audit-pro:clean')->daily();
⚡ Queue Support
Enable in .env:
AUDIT_PRO_QUEUE=true
AUDIT_PRO_QUEUE_NAME=audit-pro
Make sure a queue worker is running:
php artisan queue:work --queue=audit-pro
🧪 Testing
composer test # or vendor/bin/phpunit
🗂️ Folder Structure
laravel-audit-pro/
├── composer.json
├── phpunit.xml
├── config/
│ └── audit-pro.php
├── database/
│ └── migrations/
│ └── 2024_01_01_000001_create_activity_logs_table.php
├── resources/
│ └── views/
│ ├── layouts/
│ │ └── app.blade.php
│ ├── index.blade.php
│ └── partials/
│ └── detail.blade.php
├── routes/
│ └── web.php
├── src/
│ ├── AuditLogger.php
│ ├── AuditProServiceProvider.php
│ ├── helpers.php
│ ├── Console/Commands/
│ │ ├── CleanLogsCommand.php
│ │ └── ExportLogsCommand.php
│ ├── Facades/
│ │ └── AuditPro.php
│ ├── Http/
│ │ ├── Controllers/
│ │ │ └── ActivityLogController.php
│ │ └── Middleware/
│ │ ├── AuditProAuth.php
│ │ └── DisableLogging.php
│ ├── Jobs/
│ │ └── LogActivityJob.php
│ ├── Models/
│ │ └── ActivityLog.php
│ ├── Observers/
│ │ └── ActivityObserver.php
│ ├── Services/
│ │ └── ExportService.php
│ └── Traits/
│ └── HasActivityLog.php
└── tests/
├── TestCase.php
├── Feature/
│ └── ActivityLoggingTest.php
└── Fixtures/
└── DummyModel.php
🚢 Publishing to Packagist
- Push code to GitHub:
git push origin main - Tag a release:
git tag v1.0.0 && git push --tags - Submit at packagist.org/packages/submit
- Enable GitHub webhook for auto-updates
Versioning Strategy
| Version | Type | Example |
|---|---|---|
1.0.0 |
Initial stable release | First Packagist submit |
1.0.x |
Bug fixes | 1.0.1, 1.0.2 |
1.x.0 |
New features (backward-compat) | 1.1.0 |
2.0.0 |
Breaking changes | Major Laravel support bump |
💰 Monetisation / Pro SaaS Ideas
| Feature | Tier |
|---|---|
| Open-source core on GitHub/Packagist | Free |
| Real-time WebSocket log feed | Pro |
| Anomaly detection & alerts (email/Slack) | Pro |
| Custom dashboards & charts (Chart.js) | Pro |
| Multi-tenant SaaS with subdomain isolation | Enterprise |
| Retention policies & GDPR export tools | Enterprise |
| REST API for logs (audit log as a service) | Enterprise |
| White-label & branding customisation | Agency |
📄 License
The MIT License (MIT). Please see LICENSE.md for more information.
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 5
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-09