PHPackages                             a2zwebltd/auditable-relations - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. a2zwebltd/auditable-relations

ActiveLibrary[Database &amp; ORM](/categories/database)

a2zwebltd/auditable-relations
=============================

Automatic auditing for Eloquent relationship changes (attach, detach, sync) using Laravel Auditing

v1.1.0(1mo ago)3432↓44.6%1MITPHPPHP ^8.2

Since Jan 26Pushed 1mo agoCompare

[ Source](https://github.com/a2zwebltd/auditable-relations)[ Packagist](https://packagist.org/packages/a2zwebltd/auditable-relations)[ RSS](/packages/a2zwebltd-auditable-relations/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (4)Used By (1)

Auditable Relations
===================

[](#auditable-relations)

Automatic auditing for Eloquent relationship changes (attach, detach, sync) using Laravel Auditing.

Features
--------

[](#features)

- 🔍 **Automatic Tracking**: Captures before/after state of relationship changes
- 📝 **Detailed Logs**: Stores complete related model data, not just IDs
- 🎯 **Event-Based**: Uses `owen-it/laravel-auditing` for consistent audit logs
- ⚡ **Zero Configuration**: Works out of the box after trait inclusion
- 🔧 **Flexible**: Supports BelongsToMany and MorphToMany relationships
- 📦 **Lightweight**: Minimal overhead, maximum value

Installation
------------

[](#installation)

```
composer require a2zwebltd/auditable-relations
```

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, 12, or 13
- owen-it/laravel-auditing 13/14

Quick Start
-----------

[](#quick-start)

### 1. Implement Auditable on Your Model

[](#1-implement-auditable-on-your-model)

```
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Auditable as AuditableTrait;
use OwenIt\Auditing\Contracts\Auditable;

class Post extends Model implements Auditable
{
    use AuditableTrait;
}
```

### 2. Add the Trait and Wrap Your Relationships

[](#2-add-the-trait-and-wrap-your-relationships)

```
use A2ZWeb\AuditableRelations\Traits\AuditsRelationships;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Post extends Model implements Auditable
{
    use AuditableTrait;
    use AuditsRelationships;

    public function tags(): BelongsToMany
    {
        return $this->auditableRelation(
            $this->belongsToMany(Tag::class)
        );
    }
}
```

That's it! Now all changes to the `tags` relationship will be automatically audited.

Usage Examples
--------------

[](#usage-examples)

### Basic Usage

[](#basic-usage)

```
$post = Post::find(1);

// These operations are automatically audited
$post->tags()->attach([1, 2, 3]);
$post->tags()->detach([2]);
$post->tags()->sync([1, 3, 4]);
```

### What Gets Logged

[](#what-gets-logged)

Each operation creates an audit log entry like:

```
[
    'event' => 'synced', // or 'attached', 'detached'
    'auditable_type' => 'App\Models\Post',
    'auditable_id' => 1,
    'old_values' => [
        'tags' => [
            ['id' => 1, 'name' => 'Laravel', 'created_at' => '...'],
            ['id' => 2, 'name' => 'PHP', 'created_at' => '...'],
        ]
    ],
    'new_values' => [
        'tags' => [
            ['id' => 1, 'name' => 'Laravel', 'created_at' => '...'],
            ['id' => 3, 'name' => 'Vue', 'created_at' => '...'],
            ['id' => 4, 'name' => 'Tailwind', 'created_at' => '...'],
        ]
    ],
    'user_id' => 123,
    'user_type' => 'App\Models\User',
]
```

### Multiple Relationships

[](#multiple-relationships)

You can audit multiple relationships on the same model:

```
class Post extends Model implements Auditable
{
    use AuditableTrait;
    use AuditsRelationships;

    public function tags(): BelongsToMany
    {
        return $this->auditableRelation(
            $this->belongsToMany(Tag::class)
        );
    }

    public function categories(): BelongsToMany
    {
        return $this->auditableRelation(
            $this->belongsToMany(Category::class)
        );
    }

    public function attachments(): MorphToMany
    {
        return $this->auditableRelation(
            $this->morphToMany(File::class, 'attachable')
        );
    }
}
```

### Polymorphic Relationships

[](#polymorphic-relationships)

Works seamlessly with polymorphic relationships:

```
class Post extends Model implements Auditable
{
    use AuditableTrait;
    use AuditsRelationships;

    public function images(): MorphToMany
    {
        return $this->auditableRelation(
            $this->morphToMany(Image::class, 'imageable')
        );
    }
}
```

Supported Relationships
-----------------------

[](#supported-relationships)

- ✅ `BelongsToMany`
- ✅ `MorphToMany`
- ⏳ Other relationship types (planned)

Configuration
-------------

[](#configuration)

The package respects Laravel Auditing's global configuration:

```
// config/audit.php
return [
    'enabled' => true,        // Disable to stop all auditing
    'console' => false,       // Audit console commands
    // ... other audit config
];
```

Advanced Usage
--------------

[](#advanced-usage)

### Conditional Auditing

[](#conditional-auditing)

You can control auditing at runtime:

```
// Temporarily disable auditing
config(['audit.enabled' => false]);
$post->tags()->sync([1, 2, 3]); // Not audited
config(['audit.enabled' => true]);
```

### Custom Event Names

[](#custom-event-names)

The package uses standard event names:

- `attached` - When models are attached
- `detached` - When models are detached
- `synced` - When models are synced

### Accessing Audit Logs

[](#accessing-audit-logs)

```
use OwenIt\Auditing\Models\Audit;

// Get all audits for a model
$audits = Audit::where('auditable_type', Post::class)
    ->where('auditable_id', 1)
    ->get();

// Get relationship change audits
$relationshipAudits = Audit::where('auditable_type', Post::class)
    ->whereIn('event', ['attached', 'detached', 'synced'])
    ->get();
```

How It Works
------------

[](#how-it-works)

### Architecture

[](#architecture)

1. **Trait Application**: `AuditsRelationships` trait wraps relationship definitions
2. **Relationship Proxy**: Creates auditable versions of `BelongsToMany` and `MorphToMany`
3. **Operation Interception**: Intercepts `attach()`, `detach()`, and `sync()` calls
4. **State Capture**: Records relationship state before and after the operation
5. **Event Dispatch**: Fires `AuditCustom` event with the captured data
6. **Audit Creation**: Laravel Auditing processes the event and creates the audit log

### Performance

[](#performance)

- Minimal overhead: Only one additional query per operation (to capture current state)
- Efficient: Uses existing Laravel Auditing infrastructure
- Asynchronous-ready: Compatible with queued audit processing

Comparison with Alternatives
----------------------------

[](#comparison-with-alternatives)

Unlike other solutions:

- ✅ **Complete Data**: Stores full related model data, not just IDs
- ✅ **Native Integration**: Uses Laravel Auditing's standard audit model
- ✅ **Zero Config**: No additional tables or setup required
- ✅ **Framework-Native**: Uses Laravel's event system

Troubleshooting
---------------

[](#troubleshooting)

### Audits Not Appearing

[](#audits-not-appearing)

1. Verify auditing is enabled:

```
config('audit.enabled'); // Should be true
```

2. Check model implements `Auditable`:

```
class Post extends Model implements \OwenIt\Auditing\Contracts\Auditable
{
    use \OwenIt\Auditing\Auditable;
}
```

3. Ensure relationship is wrapped:

```
public function tags(): BelongsToMany
{
    return $this->auditableRelation( // Don't forget this!
        $this->belongsToMany(Tag::class)
    );
}
```

### Console Commands Not Audited

[](#console-commands-not-audited)

Enable console auditing in `config/audit.php`:

```
'console' => true,
```

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover a security vulnerability, please email .

Credits
-------

[](#credits)

- [A2Z Web Ltd](https://a2zweb.co)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance90

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~31 days

Total

3

Last Release

52d ago

PHP version history (2 changes)v1.0.0PHP ^8.1

v1.1.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/2b500dd3d9b470b50b1ed911cd24a6fdcce51dd97dceb4f97879f727a14495a8?d=identicon)[dawid-makowski](/maintainers/dawid-makowski)

---

Top Contributors

[![makowskid](https://avatars.githubusercontent.com/u/6271194?v=4)](https://github.com/makowskid "makowskid (2 commits)")[![nikita-a2zweb](https://avatars.githubusercontent.com/u/201099482?v=4)](https://github.com/nikita-a2zweb "nikita-a2zweb (2 commits)")

---

Tags

laraveleloquentauditingmany to manyRelationshipspivot

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/a2zwebltd-auditable-relations/health.svg)

```
[![Health](https://phpackages.com/badges/a2zwebltd-auditable-relations/health.svg)](https://phpackages.com/packages/a2zwebltd-auditable-relations)
```

###  Alternatives

[cviebrock/eloquent-sluggable

Easy creation of slugs for your Eloquent models in Laravel

4.0k13.6M253](/packages/cviebrock-eloquent-sluggable)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
