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

Audit Eloquent model changes in Laravel with a simple trait. Automatically record create/update/delete events, track who/when/what changed, and retrieve audit history for reports, compliance, and anomaly detection. Flexible drivers and rich metadata support.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Seamless Laravel Integration: Designed natively for Laravel, leveraging Eloquent events (creating, updating, deleting, restoring) to capture model changes. Aligns perfectly with Laravel’s event-driven architecture.
    • Trait-Based Implementation: Minimal boilerplate—simply use the Auditable trait on models to enable auditing. No need for manual event listeners or middleware.
    • Extensible Design: Supports custom resolvers (e.g., for IP addresses, user agents, URLs) via interfaces (UserResolver, AttributeResolver). Allows granular control over what gets audited.
    • Event Flexibility: Captures all Eloquent events (including retrieved, saved, deleted) and supports custom events via getAuditEvents().
    • Multi-Tenant/User Support: Built-in support for tracking changes by user (via UserResolver) and multi-user audits (since v7.0.0).
    • Data Redaction: Supports sensitive data masking via AttributeRedactor (e.g., hiding passwords, tokens).
    • Tagging System: Allows tagging audits for categorization (e.g., "admin_action", "api_update").
  • Cons:

    • Database-Centric: Primarily stores audits in a relational database (default). While it supports custom drivers (e.g., Redis, Elasticsearch), these require additional setup.
    • Performance Overhead: Auditing every model change adds I/O operations (database writes). May impact high-write applications unless optimized (e.g., batching, async writes).
    • Schema Dependency: Requires a dedicated audits table with specific columns (e.g., auditable_id, auditable_type, user_id, event, old_values, new_values). Schema migrations must be managed carefully.
    • Laravel Version Lock-in: Tight coupling with Laravel’s Eloquent ORM. Not easily portable to non-Laravel PHP applications.

Integration Feasibility

  • Laravel Compatibility:
    • Active Support: Officially supports Laravel 11.x–13.x (as of v14.x). If your stack is within this range, integration is straightforward.
    • Legacy Support: Older versions support Laravel 5.2–10.x, but these are end-of-life (EOL). Avoid unless maintaining legacy systems.
    • Lumen Compatibility: Tested and supported (since v8.0.2), making it viable for micro-services.
  • Database Requirements:
    • Requires a database table for audits (migration provided). Supports MySQL, PostgreSQL, SQLite, and SQL Server.
    • No additional dependencies beyond Laravel’s core.
  • PHP Version:
    • Minimum PHP 8.2 for v14.x. Ensure your environment meets this requirement.
  • Testing:
    • High test coverage (100% in some versions) and CI integration (Scrutinizer). Reliable for production use.

Technical Risk

  • Critical Risks:
    • Schema Migrations: Adding the audits table to an existing production database requires downtime or careful zero-downtime migration strategies (e.g., blue-green deployments).
    • Performance Impact: Auditing all models may slow down write-heavy operations. Mitigate by:
      • Disabling auditing for non-critical models (via audit() method or config).
      • Using a custom driver (e.g., Redis) for async writes.
      • Excluding sensitive/large attributes (e.g., old_values, new_values for text fields).
    • Data Bloat: Audits accumulate over time. Plan for:
      • Regular pruning of old audits (built-in prune() method).
      • Archiving strategies (e.g., move old audits to cold storage).
    • Concurrency Issues: Race conditions possible if multiple processes update the same model simultaneously. Laravel’s event system handles this, but custom resolvers must be thread-safe.
  • Moderate Risks:
    • Custom Resolver Complexity: Extending resolvers (e.g., for custom user tracking) requires understanding of the UserResolver interface and dependency injection.
    • Event Ordering: Auditing events may interfere with other event listeners (e.g., saving vs. updating). Test thoroughly.
    • Serialization: Complex model attributes (e.g., JSON, relationships) may not serialize/deserialize correctly. Use AttributeEncoder for custom handling.
  • Low Risks:
    • License: MIT license is permissive and poses no legal risks.
    • Community Support: Active maintainers (3.5K+ stars, Discord community) and detailed documentation reduce adoption risks.

Key Questions for the TPM

  1. Scope of Auditing:
    • Which models require auditing? Are there performance-sensitive models where auditing should be disabled?
    • Should auditing be enabled by default for all models, or opt-in/opt-out?
  2. Data Retention:
    • How long should audits be retained? Are there compliance requirements (e.g., GDPR, SOX)?
    • Will audits need to be exported/archived periodically?
  3. User Tracking:
    • How will users be resolved (e.g., authenticated users, API keys, system processes)? Custom UserResolver may be needed.
  4. Performance:
    • What is the expected write throughput? Should audits be written asynchronously?
    • Are there plans to use a custom driver (e.g., Elasticsearch for searchability)?
  5. Data Sensitivity:
    • Are there attributes that should never be audited (e.g., passwords, tokens)? Use exclude config or AttributeRedactor.
    • Should old/new values be stored for all attributes, or only changed ones?
  6. Monitoring:
    • How will audit data be queried/monitored? Will a custom API or admin panel be built?
    • Are there alerts for suspicious activities (e.g., rapid changes, unauthorized users)?
  7. Testing:
    • How will auditing be tested? Mocking events or using a test database?
    • Are there edge cases (e.g., model restoration, soft deletes) that need validation?
  8. Deployment:
    • Can the audits table migration be run in production without downtime?
    • How will the package be updated in the future (e.g., Laravel version upgrades)?

Integration Approach

Stack Fit

  • Laravel Core:
    • Eloquent Models: Ideal for any application using Eloquent. The Auditable trait integrates directly into model classes.
    • Events: Leverages Laravel’s event system (ModelEvents). No conflicts if other listeners are properly ordered.
    • Service Providers: Package registers itself via Laravel’s service container. No manual bootstrapping required.
  • Database:
    • Supported: MySQL, PostgreSQL, SQLite, SQL Server. Works with Laravel’s query builder.
    • Unsupported: NoSQL databases (e.g., MongoDB) unless using a custom driver.
  • PHP Extensions:
    • Requires PDO and database extensions (standard for Laravel).
    • PHP 8.2+ for v14.x (type safety, attributes).
  • Additional Tools:
    • Redis/Elasticsearch: For async auditing or searchable logs, requires custom driver implementation.
    • Queue Workers: Not built-in, but audits could be dispatched to a queue for async processing.

Migration Path

  1. Assessment Phase:
    • Audit current models to identify which require auditing.
    • Review existing database schema for compatibility (e.g., table/column naming conflicts).
  2. Setup:
    • Install via Composer:
      composer require owen-it/laravel-auditing
      
    • Publish configuration and migration:
      php artisan vendor:publish --provider="OwenIt\Auditing\AuditingServiceProvider"
      php artisan migrate
      
    • Configure config/auditing.php (e.g., default events, excluded attributes, resolvers).
  3. Model Integration:
    • Use the Auditable trait on target models:
      use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
      use OwenIt\Auditing\Traits\Auditable;
      
      class User extends Model implements AuditableContract
      {
          use Auditable;
      }
      
    • Customize per-model behavior:
      class User extends Model
      {
          use Auditable;
      
          public function getAuditEvents()
          {
              return ['created', 'updated', 'deleted']; // Custom events
          }
      
          public function getAuditExcludes()
          {
              return ['password', 'api_token']; // Exclude sensitive fields
          }
      }
      
  4. Resolver Configuration:
    • Extend default resolvers (e.g., for IP addresses, custom user tracking):
      use OwenIt\Auditing\Contracts\UserResolver;
      
      class CustomUserResolver implements UserResolver
      {
          public function resolve()
          {
              return auth()->user() ?: new User(); // Fallback for unauthenticated
          }
      }
      
    • Register in config/auditing.php:
      'user
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony