PHPackages                             myqaa/laravel-pivot - 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. myqaa/laravel-pivot

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

myqaa/laravel-pivot
===================

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

3.0.8(4y ago)04.4kMITPHP

Since Nov 1Pushed 4y agoCompare

[ Source](https://github.com/myQaa/laravel-pivot)[ Packagist](https://packagist.org/packages/myqaa/laravel-pivot)[ Docs](https://github.com/fico7489/laravel-pivot)[ RSS](/packages/myqaa-laravel-pivot/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (53)Used By (0)

Laravel Pivot
=============

[](#laravel-pivot)

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

Laravel Problems
----------------

[](#laravel-problems)

In Laravel events are not dispatched when BelongsToMany relation (pivot table) is updated with sync(), attach(), detach() or updateExistingPivot() methods, but this package will help with that.

Version Compatibility
---------------------

[](#version-compatibility)

Laravel VersionPackage TagSupportedDevelopment Branch&gt;= 5.5.03.\*yesmaster&lt; 5.5.0-no-- you still can use inactive branches for laravel 5.4.x or older

Install
-------

[](#install)

1.Install package with composer

```
composer require fico7489/laravel-pivot

```

With this statement, a composer will install highest available package version for your current laravel version.

2.Use Fico7489\\Laravel\\Pivot\\Traits\\PivotEventTrait trait in your base model or only in particular models.

```
use Fico7489\Laravel\Pivot\Traits\PivotEventTrait;
use Illuminate\Database\Eloquent\Model;

abstract class BaseModel extends Model
{
    use PivotEventTrait;
...
```

and that's it, enjoy.

New eloquent events
-------------------

[](#new-eloquent-events)

You can check all eloquent events here: )

New events are :

```
pivotAttaching, pivotAttached
pivotDetaching, pivotDetached,
pivotUpdating, pivotUpdated

```

The best way to catch events is with this model functions:

```
public static function boot()
{
    parent::boot();

    static::pivotAttaching(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        //
    });

    static::pivotAttached(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        //
    });

    static::pivotDetaching(function ($model, $relationName, $pivotIds) {
        //
    });

    static::pivotDetached(function ($model, $relationName, $pivotIds) {
        //
    });

    static::pivotUpdating(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        //
    });

    static::pivotUpdated(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        //
    });

    static::updating(function ($model) {
        //this is how we catch standard eloquent events
    });
}
```

You can also see those events here:

```
\Event::listen('eloquent.*', function ($eventName, array $data) {
    echo $eventName;  //e.g. 'eloquent.pivotAttached'
});
```

Suported relations
------------------

[](#suported-relations)

**BelongsToMany** and **MorphToMany**

Which events are dispatched and when they are dispatched
--------------------------------------------------------

[](#which-events-are-dispatched-and-when-they-are-dispatched)

Four BelongsToMany methods dispatches events from this package:

**attach()**
Dispatches **one** **pivotAttaching** and **one** **pivotAttached** event.
Even when more rows are added only **one** event is dispatched for all rows but in that case, you can see all changed row ids in the $pivotIds variable, and the changed row ids with attributes in the $pivotIdsAttributes variable.

**detach()**
Dispatches **one** **pivotDetaching** and **one** **pivotDetached** event.
Even when more rows are deleted only **one** event is dispatched for all rows but in that case, you can see all changed row ids in the $pivotIds variable.

**updateExistingPivot()**
Dispatches **one** **pivotUpdating** and **one** **pivotUpdated** event.
You can change only one row in the pivot table with updateExistingPivot.

**sync()**
Dispatches **more** **pivotAttaching** and **more** **pivotAttached** events, depending on how many rows are added in the pivot table. These events are not dispatched if nothing is attached.
Dispatches **one** **pivotDetaching** and **one** **pivotDetached** event, but you can see all deleted ids in the $pivotIds variable. This event is not dispatched if nothing is detached.
E.g. when you call sync() if two rows are added and two are deleted **two** **pivotAttaching** and **two** **pivotAttached** events and **one** **pivotDetaching** and **one** **pivotDetached** event will be dispatched.
If sync() is called but rows are not added or deleted events are not dispatched.

Usage
-----

[](#usage)

We have three tables in database users(id, name), roles(id, name), role\_user(user\_id, role\_id). We have two models :

```
class User extends Model
{
    use PivotEventTrait;
    ....

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    static::pivotAttached(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        echo 'pivotAttached';
        echo get_class($model);
        echo $relationName;
        print_r($pivotIds);
        print_r($pivotIdsAttributes);
    });

    static::pivotUpdated(function ($model, $relationName, $pivotIds, $pivotIdsAttributes) {
        echo 'pivotUpdated';
        echo get_class($model);
        echo $relationName;
        print_r($pivotIds);
        print_r($pivotIdsAttributes);
    });

    static::pivotDetached(function ($model, $relationName, $pivotIds) {
        echo 'pivotDetached';
        echo get_class($model);
        echo $relationName;
        print_r($pivotIds);
    });
```

```
class Role extends Model
{
    ....
```

### Attaching

[](#attaching)

For attach() or detach() one event is dispatched for both pivot ids.

#### Attaching with int

[](#attaching-with-int)

Running this code

```
$user = User::first();
$user->roles()->attach(1);
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1]
[1 => []]

```

#### Attaching with array

[](#attaching-with-array)

Running this code

```
$user = User::first();
$user->roles()->attach([1]);
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1]
[1 => []]

```

#### Attaching with model

[](#attaching-with-model)

Running this code

```
$user = User::first();
$user->roles()->attach(Role::first());
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1]
[1 => []]

```

#### Attaching with collection

[](#attaching-with-collection)

Running this code

```
$user = User::first();
$user->roles()->attach(Role::get());
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1, 2]
[1 => [], 2 => []]

```

#### Attaching with array (id =&gt; attributes)

[](#attaching-with-array-id--attributes)

Running this code

```
$user = User::first();
$user->roles()->attach([1, 2 => ['attribute' => 'test']], ['attribute2' => 'test2']);
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1, 2]
[1 => [], 2 => ['attribute' => 'test', 'attribute2' => 'test2']]

```

### Syncing:

[](#syncing)

For sync() method event is dispatched for each pivot row.

Running this code

```
$user = User::first();
$user->roles()->sync([1, 2]);
```

You will see this output

```
pivotAttached
App\Models\User
roles
[1]
[1 => []]

pivotAttached
App\Models\User
roles
[2]
[2 => []]

```

### Detaching:

[](#detaching)

Running this code

```
$user = User::first();
$user->roles()->detach([1, 2]);
```

You will see this output

```
pivotDetached
App\Models\User
roles
[1, 2]

```

### Updating:

[](#updating)

Running this code

```
$user = User::first();
$user->roles()->updateExistingPivot(1, ['attribute' => 'test']);
```

You will see this output

```
pivotUpdated
App\Models\User
roles
[1]
[1 => ['attribute' => 'test']]

```

License
-------

[](#license)

MIT

**Free Software, Hell Yeah!**

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 79.8% 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

Recently: every ~165 days

Total

50

Last Release

1576d ago

Major Versions

1.2.2 → 2.1.32017-12-10

1.2.3 → 2.1.42017-12-14

1.2.4 → 2.2.42018-02-12

1.2.6 → 2.2.72018-07-28

2.3.x-dev → 3.0.02018-11-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/0ae40dc64b6b61c058f0f3a665880ed3bdfa735f3b3bccefbd0f51a5077c6d8a?d=identicon)[githubmyqaa](/maintainers/githubmyqaa)

---

Top Contributors

[![fico7489](https://avatars.githubusercontent.com/u/4559663?v=4)](https://github.com/fico7489 "fico7489 (130 commits)")[![lewisf2001uk](https://avatars.githubusercontent.com/u/11738262?v=4)](https://github.com/lewisf2001uk "lewisf2001uk (7 commits)")[![joostbaptist](https://avatars.githubusercontent.com/u/8181757?v=4)](https://github.com/joostbaptist "joostbaptist (6 commits)")[![mikebronner](https://avatars.githubusercontent.com/u/1791050?v=4)](https://github.com/mikebronner "mikebronner (6 commits)")[![SonarSoftware](https://avatars.githubusercontent.com/u/12124408?v=4)](https://github.com/SonarSoftware "SonarSoftware (3 commits)")[![tomschlick](https://avatars.githubusercontent.com/u/70184?v=4)](https://github.com/tomschlick "tomschlick (2 commits)")[![imanghafoori1](https://avatars.githubusercontent.com/u/6961695?v=4)](https://github.com/imanghafoori1 "imanghafoori1 (2 commits)")[![robertvansteen](https://avatars.githubusercontent.com/u/14931924?v=4)](https://github.com/robertvansteen "robertvansteen (2 commits)")[![amadeann](https://avatars.githubusercontent.com/u/14104292?v=4)](https://github.com/amadeann "amadeann (2 commits)")[![Roman77450](https://avatars.githubusercontent.com/u/43234201?v=4)](https://github.com/Roman77450 "Roman77450 (1 commits)")[![jonathanpmartins](https://avatars.githubusercontent.com/u/6137992?v=4)](https://github.com/jonathanpmartins "jonathanpmartins (1 commits)")[![erikgaal](https://avatars.githubusercontent.com/u/1234268?v=4)](https://github.com/erikgaal "erikgaal (1 commits)")

---

Tags

laravel pivot eventslaravel BelongsToMany eventseloquent extra eventslaravel sync eventseloquent events

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/myqaa-laravel-pivot/health.svg)

```
[![Health](https://phpackages.com/badges/myqaa-laravel-pivot/health.svg)](https://phpackages.com/packages/myqaa-laravel-pivot)
```

###  Alternatives

[fico7489/laravel-pivot

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

5256.0M21](/packages/fico7489-laravel-pivot)[genealabs/laravel-pivot-events

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

1404.9M8](/packages/genealabs-laravel-pivot-events)[mikebronner/laravel-pivot-events

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

140459.5k7](/packages/mikebronner-laravel-pivot-events)[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[staudenmeir/eloquent-json-relations

Laravel Eloquent relationships with JSON keys

1.1k5.8M24](/packages/staudenmeir-eloquent-json-relations)[gearbox-solutions/eloquent-filemaker

A package for getting FileMaker records as Eloquent models in Laravel

6454.8k2](/packages/gearbox-solutions-eloquent-filemaker)

PHPackages © 2026

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