codersandip/laravel-audit-pro
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.
codersandip/laravel-audit-pro 适用场景与选型建议
codersandip/laravel-audit-pro 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「logging」 「admin」 「Audit」 「observer」 「laravel」 「activity-log」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 codersandip/laravel-audit-pro 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 codersandip/laravel-audit-pro 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 codersandip/laravel-audit-pro 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Log adding/updating/deleting of elements
Doctrine ORM provider for the auditor audit-log library.
2lenet/EasyAdminPlusBundle
A Zend Framework module that sets up Monolog for logging in applications.
PB Web Media Audit Bundle for Symfony
Analysis module for finding problematical shop data.
统计信息
- 总下载量: 6
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-09