Search code examples
phplaravellaravel-auditing

Laravel Auditing Duplicate Auditing Entries


I followed the instructions from the laravel auditing docs to install it in my project.

Afterwards I edited my laravel model:

class MyModel extends Model implements Auditable
{
    use CamelCaseAttributes;
    use AuditingAuditable;
...

Now I see the entries in the audits table but it seems that for every action (created/updated/etc.) there are 2 identical entries. I checked the query output using DB::enableQueryLog and DB::getQueryLog which shows 1 Update query and 2 inserts into the audits table with the same values.

Any ideas how to avoid the duplicate entries?

php => 8.0
laravel => 8.0
laravel-audits => 13.6

Solution

  • Alright after debugging the issue for quite some time I noticed that the Auditing event was fired twice for every send.

    The issue was the booted method in the model:

    class MyModel extends Model implements Auditable
    {
        use CamelCaseAttributes;
        use AuditingAuditable;
    
        protected static function booted()
        {
            static::addGlobalScope(new CustomScope());
    
            parent::booted(); // this line is the issue
        }
    ...
    

    The Auditable trait was initialized twice since the laravel Model which is my base class recursivly initializes the traits on the class in its booted() method. This causes 2 auditing events and therefor 2 db entries.

    Fix was to remove the parent::booted(); line completly since the constructor of the laravel Model::class is enough to set everything up.