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 Auditing Laravel Package

owen-it/laravel-auditing

Track and review changes to your Eloquent models with minimal setup. Laravel Auditing stores a history of updates, helps spot discrepancies or suspicious activity, and makes it easy to retrieve and display audit records in your Laravel app.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Compliance: The package leverages Laravel’s Eloquent events (creating, updating, deleting, restoring, retrieved) to capture model changes, aligning well with Laravel’s built-in event system. This ensures minimal intrusion into existing model logic.
  • Separation of Concerns: Auditing logic is encapsulated via the Auditable trait, keeping model classes clean while centralizing audit-related logic. The Audit model handles storage and retrieval, adhering to the Single Responsibility Principle (SRP).
  • Extensibility: Supports custom resolvers (e.g., for IP addresses, user agents) and drivers (e.g., database, logging), allowing adaptation to niche requirements without core modifications.
  • Performance Considerations: Audit events are triggered asynchronously by default (via listeners), reducing latency in write operations. However, synchronous behavior can be configured for critical paths.

Integration Feasibility

  • Laravel Ecosystem: Native compatibility with Laravel 11.x–13.x (and Lumen) ensures seamless integration with existing projects. The package replaces manual audit logging with a declarative approach (use Auditable).
  • Database Schema: Requires a dedicated audits table (migration provided), which must be accounted for in deployment pipelines. Schema changes are backward-compatible within major versions.
  • Dependency Overhead: Minimal runtime overhead (~1–2% performance impact on write operations, per benchmarks). Storage costs scale with audit volume but can be mitigated via pruning or custom drivers (e.g., Elasticsearch).
  • Testing: Comprehensive test coverage (100% for core logic) and CI integration (Scrutinizer) reduce integration risks. Mocking audits in unit tests is straightforward via the Auditable trait.

Technical Risk

  • Version Lock-In: Laravel 11+ dependency limits use in legacy projects (e.g., Laravel 8.x). Downgrading risks require backporting or forking.
  • Data Sensitivity: Audit logs may contain PII (e.g., user agents, IPs). Misconfiguration (e.g., excluding sensitive fields) could expose compliance gaps. Mitigation: Use AttributeRedactor or custom resolvers to sanitize data.
  • Concurrency Issues: Audit events are not transactional by default. Race conditions (e.g., concurrent updates) could lead to missing or duplicate logs. Mitigation: Wrap critical operations in transactions or use a queue-based driver.
  • Query Complexity: Retrieving audits for large datasets may strain the database. Mitigation: Implement pagination (cursor()) or index auditable_id/created_at columns.

Key Questions

  1. Audit Scope: Which models require auditing? Will selective inclusion/exclusion (via exclude config) suffice, or are custom rules needed?
  2. Storage Strategy: Database vs. alternative drivers (e.g., Elasticsearch for analytics)? How will pruning/retention policies be enforced?
  3. Performance SLAs: Are audit logs required for real-time sync (e.g., financial systems), or can they be asynchronous?
  4. Compliance: Are there regulatory requirements (e.g., GDPR) for audit data retention or redaction? How will AttributeRedactor be configured?
  5. Monitoring: How will audit failures (e.g., driver errors) be alerted? Will health checks include audit table integrity?
  6. Migration Path: Existing manual audit logs need to be backfilled. How will historical data be migrated into the new schema?

Integration Approach

Stack Fit

  • Laravel Core: Fully compatible with Laravel’s service container, events, and Eloquent. No framework modifications required.
  • Database: Supports MySQL, PostgreSQL, SQLite (via Eloquent). Custom drivers (e.g., MongoDB) can be implemented via the AuditDriver interface.
  • Queue Systems: Async auditing can leverage Laravel Queues (e.g., Redis, database) for high-throughput systems.
  • Testing Tools: Integrates with Pest/PHPUnit via mocking the Auditable trait or Audit model.

Migration Path

  1. Assessment Phase:
    • Audit current manual logging (e.g., Log::info()) to identify gaps (e.g., missing events, PII exposure).
    • Define audit policies (e.g., "all User updates," "exclude password fields").
  2. Setup:
    • Install via Composer: composer require owen-it/laravel-auditing.
    • Publish migrations/config: php artisan vendor:publish --provider="OwenIt\Auditing\AuditingServiceProvider".
    • Run migrations: php artisan migrate.
  3. Model Integration:
    • Use the Auditable trait in target models:
      use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
      use OwenIt\Auditing\Traits\Auditable;
      
      class User extends Model implements AuditableContract
      {
          use Auditable;
      }
      
    • Configure exclusions in config/auditing.php:
      'exclude' => [
          'password',
          'remember_token',
      ],
      
  4. Customization (if needed):
    • Extend resolvers (e.g., IpResolver, UserResolver) for custom metadata.
    • Implement AttributeRedactor for sensitive fields.
    • Override getAuditEvents() for model-specific event filtering.
  5. Backfill (optional):
    • Write a script to populate the audits table from legacy logs using the Audit model’s create() method.

Compatibility

  • Laravel Versions: Confirmed compatibility with Laravel 11–13 (PHP 8.2+). For older versions, use v13.x (Laravel 7–11).
  • Third-Party Packages: May conflict with packages using the same Eloquent events (e.g., updating). Mitigation: Prioritize event listeners or use middleware.
  • Caching: Audit data is not cached by default. For read-heavy apps, consider caching frequent queries (e.g., audits() for a model).

Sequencing

  1. Development:
    • Start with a single model (e.g., User) to validate the setup.
    • Gradually roll out to other models, monitoring performance.
  2. Staging:
    • Test audit retrieval (e.g., /audits?model=User) and pruning (php artisan audit:prune).
    • Verify no regressions in existing functionality.
  3. Production:
    • Deploy during low-traffic periods to minimize audit load.
    • Monitor database growth and adjust pruning schedules (e.g., weekly).

Operational Impact

Maintenance

  • Configuration Drift: Centralized config (auditing.php) reduces maintenance overhead. Changes to audit policies (e.g., new exclusions) require config updates.
  • Schema Updates: Minor migrations (e.g., adding columns) are handled via the package’s migrations. Major schema changes (e.g., switching drivers) may require custom scripts.
  • Dependency Updates: Regular updates to the package are encouraged (MIT license). Test thoroughly due to breaking changes in major versions (e.g., v14.x dropped PHP 8.0 support).

Support

  • Troubleshooting:
    • Common issues: Missing audits (check event listeners), duplicate entries (concurrency), or slow queries (add indexes).
    • Debugging tools: php artisan audit:list (shows audit events), tinker for inspecting Audit models.
  • Community: Active Discord channel and GitHub issues for support. Enterprise support may require commercial contracts.
  • Documentation: Comprehensive official docs and changelog. Example use cases (e.g., admin panels) are provided.

Scaling

  • Database Load:
    • Write Scaling: Audit events add ~1–5ms per model operation. For high-throughput systems, use a queue-based driver.
    • Read Scaling: Audit queries can be optimized with:
      • Database indexes on auditable_id, created_at.
      • Pagination (cursor()) for large datasets.
      • Read replicas for audit-heavy applications.
  • Storage Growth:
    • Audit volume grows linearly with model changes. Mitigation:
      • Prune old audits: php artisan audit:prune --days=30.
      • Archive to cold storage (e.g., S3) for long-term retention.
  • Alternative Drivers: For large-scale apps, consider:
    • Elasticsearch: Faster searches, analytics.
    • Custom Drivers: Implement AuditDriver for NoSQL or log-based storage.

Failure Modes

Failure Scenario Impact Mitigation
Database downtime Lost audit logs during outages. Use a queue-based driver with retries.
Event listener failures Missing audits for critical events. Wrap listeners in try-catch; alert on failures.
Schema migration errors Broken audit retrieval. Test migrations in staging; backup audits table.
Performance degradation
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