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

ss-ipg/laravel-auditable

Attribute-based audit logging for Laravel Eloquent models. Add #[Auditable] to track create/update/delete/soft delete/restore events with old/new values, column include/exclude/redact, per-model event filters, JSON formatting, and extensible context providers.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Declarative Design: Leverages PHP 8.3+ attributes for zero-boilerplate audit logging, aligning with modern Laravel (11+) practices. Reduces cognitive load by centralizing audit logic in model definitions.
  • Event-Driven: Integrates seamlessly with Eloquent’s lifecycle events (creating, updating, deleting), ensuring minimal performance overhead (only active during model operations).
  • Extensibility: Supports context providers and custom formatters, enabling integration with third-party tools (e.g., Datadog, Splunk) or internal systems (e.g., SIEM).
  • Soft Delete Awareness: Automatically distinguishes between soft_deleted and deleted events, critical for compliance-heavy applications (e.g., healthcare, finance).

Integration Feasibility

  • Laravel 11+ Only: Requires PHP 8.3+, which may necessitate dependency updates if the current stack is older. Compatibility with Laravel 11+ ensures alignment with long-term support (LTS) roadmaps.
  • Minimal Configuration: Only requires:
    1. Composer install.
    2. Log channel setup (config/logging.php).
    3. Environment flag (AUDITABLE_ENABLED=true). Migration path: Low-risk for greenfield projects; brownfield projects may need event listener refactoring if existing audit logic relies on observers/events.
  • Database Impact: No schema changes; logs are written to the configured log channel (e.g., storage/logs/audit.log). No additional tables required, reducing deployment complexity.

Technical Risk

  • Mass Assignment Bypass: Query builder operations (e.g., Model::update([...])) do not trigger audits, requiring developer discipline to use model instances for critical operations. Mitigation: Document this in team guidelines or enforce via custom validation.
  • Performance: Audit logging adds ~5–15ms per model operation (benchmark-dependent). For high-volume systems (e.g., >10K ops/sec), consider:
    • Async logging (e.g., queue-based).
    • Selective auditing (e.g., exclude high-frequency models).
  • Testing Complexity: Audit::fake() simplifies unit tests but may require adjustments to existing test suites if they mock events directly.
  • Redaction Logic: Column redacting is client-side only; sensitive data in logs could still leak if log files are improperly secured. Mitigation: Combine with file-level encryption (e.g., Laravel Forge’s log encryption).

Key Questions

  1. Compliance Requirements:
    • Are immutable audit logs required (e.g., write-only database tables)? If so, this package’s file-based logs may not suffice.
    • Does the organization need tamper-evident logs (e.g., cryptographic hashes)? If yes, extend with a custom formatter.
  2. Performance Constraints:
    • What is the maximum acceptable latency for audit operations? Stress-test with production-like workloads.
    • Are there hot paths (e.g., checkout flows) where auditing should be disabled?
  3. Tooling Integration:
    • Will logs be consumed by SIEM tools (e.g., Splunk, ELK)? If so, validate the JSON formatter’s compatibility.
    • Is real-time monitoring of audit events needed (e.g., Slack alerts for critical changes)?
  4. Deployment Strategy:
    • How will audit logs be archived/retired? The package doesn’t include retention policies (handled by Laravel’s log channel).
    • Are there multi-region deployments requiring log aggregation (e.g., AWS CloudWatch, Datadog)?
  5. Customization Needs:
    • Are additional context fields required (e.g., request IDs, tenant IDs)? Extend via AuditContextProvider.
    • Should audit logs include nested relationships (e.g., changes to hasMany models)? This is out-of-scope; may need custom event listeners.

Integration Approach

Stack Fit

  • Laravel 11+: Native support for PHP 8.3 attributes and modern Laravel features (e.g., enums, first-class type hints).
  • PHP 8.3+: Enables attribute-based metadata, reducing verbosity compared to traditional observer/event patterns.
  • Logging Stack: Compatible with any Laravel log channel (e.g., single, daily, syslog, or third-party like Monolog). Recommended: Use daily with rotation for compliance.
  • Testing: Audit::fake() integrates with Laravel’s testing helpers (e.g., assertLogged), reducing test maintenance overhead.

Migration Path

Current State Migration Steps Risks/Mitigations
No auditing 1. Add #[Auditable] to critical models. 2. Configure log channel. 3. Enable via .env. None.
Custom observers/events 1. Replace observers with attributes. 2. Update tests to use Audit::fake(). 3. Remove obsolete event listeners. Breakage: Ensure all audit logic is migrated (e.g., custom context). Use feature flags for gradual rollout.
Third-party audit packages 1. Compare feature parity (e.g., column filtering, soft deletes). 2. Pilot with non-critical models. 3. Phase out old package. Data loss: Validate log formats match compliance requirements.
Database-triggered audits 1. Replicate audit logic in PHP (e.g., triggers → attributes). 2. Compare performance. 3. Deprecate triggers if PHP-based audits are sufficient. Performance: Database triggers may outperform PHP for high-volume systems. Benchmark both approaches.

Compatibility

  • Eloquent Models: Works with all Eloquent models (including SoftDeletes, Timestamps).
  • Pivot Tables: Requires custom pivot models for auditing many-to-many relationships.
  • API Resources: No direct integration, but logs can be used to validate API responses (e.g., ensure updated_at matches audit timestamps).
  • Queued Jobs: Audit logs reflect the job’s execution context (e.g., user_id from job payload). For async operations, ensure jobs include necessary context (e.g., auth()->setUser($user)).

Sequencing

  1. Pilot Phase:
    • Enable auditing for 1–2 low-risk models (e.g., User, Setting).
    • Validate log format, performance, and compliance with requirements.
  2. Gradual Rollout:
    • Prioritize high-value models (e.g., Payment, PatientRecord).
    • Exclude high-frequency models (e.g., Session, Log) unless critical.
  3. Testing:
    • Unit tests: Use Audit::fake() to verify model operations.
    • Integration tests: Ensure logs appear in expected channels (e.g., storage/logs/audit.log).
    • Load tests: Simulate production traffic to measure performance impact.
  4. Production:
    • Enable via .env in staging first.
    • Monitor log volume and performance metrics (e.g., audit.log file size, disk I/O).

Operational Impact

Maintenance

  • Low Ongoing Effort:
    • No database migrations or schema changes.
    • Updates are Composer-based (no manual code changes for new versions).
  • Configuration Drift Risk:
    • Attribute options (e.g., columns, exclude) are co-located with models, reducing misconfiguration risk.
  • Deprecation:
    • Laravel 11+ only; align with LTS support cycles (e.g., drop PHP 8.2 support when Laravel 12 EOLs it).

Support

  • Troubleshooting:
    • Common Issues:
      • Missing logs: Verify AUDITABLE_ENABLED=true and log channel exists.
      • Incomplete changes: Check for mass assignment operations (e.g., Model::update()).
      • Performance: Use tideways/xhprof to profile audit overhead.
    • Debugging Tools:
      • Audit::logged() for runtime inspection.
      • Laravel’s log:tail for real-time log monitoring.
  • Documentation:
    • Internal Runbook Needed:
      • How to disable auditing for performance (e.g., config(['auditable.enabled' => false])).
      • How to recover from log corruption (e.g., restore from backups).
      • Compliance checklist: Ensure logs meet retention/immutability requirements.

Scaling

  • Horizontal Scaling:
    • Logs are file-based by default; for distributed systems, use a centralized log aggregator (e.g., ELK, Datadog).
    • Async Logging: Off
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui