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

Audit Bundle Laravel Package

benmacha/audit-bundle

Symfony bundle to audit Doctrine entity changes with rollback support. Includes a web UI and REST API to browse audit logs, flexible configuration, security integration, and optional async processing. Supports PHP 7.4–8.4 and Symfony 5.4–7.x.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require benmacha/audit-bundle
    

    Symfony Flex auto-configures the bundle.

  2. Enable Auditing: Add #[Auditable] to your entity:

    use BenMacha\AuditBundle\Attribute\Auditable;
    
    #[ORM\Entity]
    #[Auditable] // Tracks all operations by default
    class User { ... }
    
  3. First Use Case: Access the web UI at /admin/audit (default route) or use the API at /api/audit/logs.


Implementation Patterns

1. Entity-Level Auditing

  • Pattern: Use #[Auditable] on entities to enable automatic tracking.
  • Example:
    #[Auditable(
        operations: ['create', 'update'], // Exclude 'delete'
        ignoredFields: ['password', 'apiToken']
    )]
    class Product { ... }
    

2. Field-Level Control

  • Pattern: Use #[IgnoreAudit] or #[AuditSensitive] for granular control.
  • Example:
    class User {
        #[IgnoreAudit] private string $password;
        #[AuditSensitive(mask: true)] private string $ssn;
    }
    

3. Custom Metadata

  • Pattern: Add context to audit logs with #[AuditContext] or #[AuditMetadata].
  • Example:
    #[AuditContext(reason: 'Admin update', category: 'user_management')]
    class User { ... }
    

4. Event-Driven Extensions

  • Pattern: Subscribe to audit events for custom logic.
  • Example:
    use BenMacha\AuditBundle\Event\AuditEvents;
    
    class AuditSubscriber {
        public static function getSubscribedEvents(): array {
            return [AuditEvents::POST_AUDIT => 'onPostAudit'];
        }
    
        public function onPostAudit(AuditEvent $event) {
            $this->notifyAdmin($event->getAuditLog());
        }
    }
    

5. API Integration

  • Pattern: Use the REST API for programmatic access.
  • Example:
    # Fetch logs for a specific entity
    curl -X GET "/api/audit/logs/entity/App\Entity\User/1"
    

6. Rollback Workflows

  • Pattern: Implement rollback logic in services.
  • Example:
    public function revertOrder(Order $order, int $auditLogId) {
        $this->auditService->rollbackEntity($auditLogId);
        $this->notifyCustomer($order);
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Enable async_processing: true in audit.yaml for large-scale apps.
    • Monitor batch_size to avoid locking issues.
  2. Sensitive Data Exposure:

    • Always use #[AuditSensitive] for PII (e.g., passwords, SSNs).
    • Mask fields in the UI with mask: true.
  3. Event Ordering:

    • PRE_AUDIT events can modify logs before saving, but avoid infinite loops.
  4. Database Bloat:

    • Set retention_days in config to auto-purge old logs.
    • Run php bin/console audit:cleanup periodically.
  5. Security Misconfigurations:

    • Ensure manage_role and rollback_role are restricted to admins.
    • Use AUDIT_ENABLED=false in production .env if auditing is unnecessary.

Debugging Tips

  • Log Level: Set AUDIT_LOG_LEVEL=debug in .env for verbose logs.
  • Event Debugging: Dump AuditEvent objects in subscribers:
    public function onPostAudit(AuditEvent $event) {
        \dump($event->getAuditLog()->toArray());
    }
    
  • API Testing: Use Postman to test endpoints like /api/audit/rollback/{id}.

Extension Points

  1. Custom Storage: Override the default Doctrine storage by implementing AuditStorageInterface.

  2. UI Customization: Extend Twig templates in templates/bundles/AuditBundle/.

  3. Rollback Validation: Subclass AuditRollbackService to add pre-rollback checks.

  4. Async Processing: Configure messenger transport in audit.yaml for background jobs.

Configuration Quirks

  • Auto-Discovery: If entities aren’t audited, verify auto_discover: true in audit.yaml.
  • Field Names: Use exact field names (case-sensitive) in ignoredFields.
  • Route Conflicts: Prefix routes with route_prefix if /admin/audit clashes with other routes.

Pro Tips

  • Selective Auditing: Disable auditing for non-critical entities:
    audit:
        entities:
            App\Entity\LogEntry:
                enabled: false
    
  • Search Optimization: Use indexed: true in #[AuditMetadata] for frequently searched fields.
  • Rollback Testing: Test rollbacks in staging with:
    php bin/console audit:rollback --dry-run
    
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