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

Doctrine Audit Laravel Package

drjele/doctrine-audit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require drjele/doctrine-audit
    

    Ensure your project uses Doctrine ORM (v2.5+).

  2. Configuration Add the bundle to config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel via doctrine/orm bridge):

    // Laravel (if using Symfony components)
    $provider = new \DrJele\DoctrineAudit\DoctrineAuditBundle();
    $this->registerServiceProvider($provider);
    
  3. First Audit Enable auditing for an entity (e.g., User):

    use DrJele\DoctrineAudit\Annotation as ORMAudit;
    
    /**
     * @ORM\Entity
     * @ORMAudit\Audit
     */
    class User { ... }
    

    Or via YAML/XML if using annotations.

  4. Trigger Audits Doctrine events (prePersist, preUpdate, preRemove) automatically log changes. Verify with:

    $auditLog = $entityManager->getRepository(AuditLog::class)->findBy(['entity' => User::class]);
    

Implementation Patterns

Workflow: Tracking Changes

  1. Annotate Entities Use @Audit on entities and @AuditField on properties to specify tracked fields:

    /**
     * @ORMAudit\AuditField(fieldName="email", fieldType="string")
     */
    private $email;
    
  2. Customize Audit Metadata Override default metadata (e.g., auditTable, logEntity) via:

    # config/packages/drjele_doctrine_audit.yaml
    drjele_doctrine_audit:
        audit_table: 'custom_audit_logs'
        log_entity: App\Entity\CustomAuditLog
    
  3. Query Audits Fetch changes for a specific entity:

    $audits = $entityManager->getRepository(AuditLog::class)
        ->findBy(['entityClass' => User::class, 'field' => 'email']);
    
  4. Soft-Deletes Extend AuditLog to include soft-delete logic:

    use DrJele\DoctrineAudit\Model\AuditLog as BaseAuditLog;
    
    class AuditLog extends BaseAuditLog {
        public function isDeleted(): bool { ... }
    }
    

Integration Tips

  • Laravel-Specific: Use doctrine/orm via spatie/laravel-doctrine-orm for seamless integration.
  • Event Listeners: Attach custom logic to postAudit events:
    $eventManager->addEventListener(
        Events::POST_AUDIT,
        [$this, 'onPostAudit']
    );
    
  • Batch Operations: Disable auditing for bulk operations:
    $entityManager->getConnection()->getConfiguration()->setSQLLogger(null);
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Auditing every field on every save can slow down writes. Use @AuditField selectively.
    • Fix: Exclude sensitive fields (e.g., passwords) or use auditIgnoreFields.
  2. Entity Manager Scope

    • Audits are tied to the current EntityManager. Ensure the same EM is used across transactions.
    • Fix: Pass the EM explicitly if managing multiple instances.
  3. Annotation Conflicts

    • Doctrine annotations (e.g., @ORM\Column) may clash with @AuditField.
    • Fix: Use full namespace (@DrJele\DoctrineAudit\Annotation\AuditField).
  4. Missing Audit Logs

    • If audits aren’t recorded, verify:
      • The entity has @Audit.
      • The AuditLog entity is mapped (check drjele_doctrine_audit.log_entity).
      • Doctrine events are subscribed (check DoctrineAuditBundle registration).

Debugging Tips

  • Enable SQL Logging
    $entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  • Check Event Subscribers Inspect DoctrineAuditBundle's services.yaml for registered listeners.

Extension Points

  1. Custom Audit Log Extend AuditLog to add fields (e.g., ipAddress):

    class CustomAuditLog extends AuditLog {
        /**
         * @ORM\Column(type="string", nullable=true)
         */
        private $ipAddress;
    }
    

    Update drjele_doctrine_audit.log_entity to point to CustomAuditLog.

  2. Dynamic Field Auditing Use a listener to audit fields conditionally:

    public function onPreFlush(PreFlushEventArgs $args) {
        $entity = $args->getEntity();
        if ($entity instanceof User && $entity->isSensitiveUpdate()) {
            $args->getObjectManager()->getEventManager()->addEventListener(
                Events::PRE_UPDATE,
                [$this, 'auditSensitiveFields']
            );
        }
    }
    
  3. Asynchronous Auditing Offload audits to a queue (e.g., Symfony Messenger) to avoid blocking writes:

    $eventDispatcher->dispatch(new AuditEvent($entity, $action), Events::POST_AUDIT);
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope