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

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

fico7489/laravel-pivot
======================

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

3.0.13(1y ago)5256.0M—3.2%47[2 issues](https://github.com/fico7489/laravel-pivot/issues)[1 PRs](https://github.com/fico7489/laravel-pivot/pulls)20MITPHPCI failing

Since Nov 1Pushed 1y ago14 watchersCompare

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

READMEChangelog (10)Dependencies (3)Versions (62)Used By (20)

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.
Dispatches **more** **pivotUpdating** and **more** **pivotUpdated** events, depending on how many rows are updated in the pivot table. These events are not dispatched if nothing is attached.

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

61

—

FairBetter than 99% of packages

Maintenance49

Moderate activity, may be stable

Popularity65

Solid adoption and visibility

Community38

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 80.3% 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 ~51 days

Recently: every ~205 days

Total

55

Last Release

378d 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/949b29f724c44fb480deeab36c7c50624f1351bec04a5045546f6d9f7334dd27?d=identicon)[fico7489](/maintainers/fico7489)

---

Top Contributors

[![fico7489](https://avatars.githubusercontent.com/u/4559663?v=4)](https://github.com/fico7489 "fico7489 (155 commits)")[![lewisf2001uk](https://avatars.githubusercontent.com/u/11738262?v=4)](https://github.com/lewisf2001uk "lewisf2001uk (7 commits)")[![mikebronner](https://avatars.githubusercontent.com/u/1791050?v=4)](https://github.com/mikebronner "mikebronner (6 commits)")[![joostbaptist](https://avatars.githubusercontent.com/u/8181757?v=4)](https://github.com/joostbaptist "joostbaptist (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)")[![cheesegrits](https://avatars.githubusercontent.com/u/934456?v=4)](https://github.com/cheesegrits "cheesegrits (2 commits)")[![imanghafoori1](https://avatars.githubusercontent.com/u/6961695?v=4)](https://github.com/imanghafoori1 "imanghafoori1 (2 commits)")[![Jxckaroo](https://avatars.githubusercontent.com/u/24681027?v=4)](https://github.com/Jxckaroo "Jxckaroo (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)")[![sowrensen](https://avatars.githubusercontent.com/u/13097375?v=4)](https://github.com/sowrensen "sowrensen (1 commits)")[![erikgaal](https://avatars.githubusercontent.com/u/1234268?v=4)](https://github.com/erikgaal "erikgaal (1 commits)")[![jonathanpmartins](https://avatars.githubusercontent.com/u/6137992?v=4)](https://github.com/jonathanpmartins "jonathanpmartins (1 commits)")[![PHLAK](https://avatars.githubusercontent.com/u/53531?v=4)](https://github.com/PHLAK "PHLAK (1 commits)")

---

Tags

attach-eventsbelongstomany-eventseloquent-eventslaravellaravel-eventspivot-eventssync-eventlaravel pivot eventslaravel BelongsToMany eventseloquent extra eventslaravel sync eventseloquent events

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[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)[cybercog/laravel-ownership

Laravel Ownership simplify management of Eloquent model's owner.

9126.6k3](/packages/cybercog-laravel-ownership)

PHPackages © 2026

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