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

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

mikebronner/laravel-pivot-events
================================

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

13.1.0(2mo ago)140459.5k—1.7%125MITPHPPHP ^8.2CI passing

Since May 17Pushed 2mo ago1 watchersCompare

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

READMEChangelog (10)Dependencies (10)Versions (23)Used By (5)

Laravel Pivot Events
====================

[](#laravel-pivot-events)

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

This package is a fork of [fico7489/laravel-pivot](https://github.com/fico7489/laravel-pivot)created mainly to address compatibility issues with [Laravel Telescope](https://github.com/laravel/telescope) and [Model Caching for Laravel](https://github.com/GeneaLabs/laravel-model-caching).

Sponsors
--------

[](#sponsors)

We thank the following sponsors for their generosity. Please take a moment to check them out:

- [LIX](https://lix-it.com)

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

[](#requirements)

- Laravel 11.0+
- PHP 8.2+

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

[](#installation)

1.Install package with composer: `composer require "mikebronner/laravel-pivot-events:*"`

2. Use `GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait` trait in your base model or only in particular models. ```
    // ...
    use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
    use Illuminate\Database\Eloquent\Model;

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

New Eloquent Events
-------------------

[](#new-eloquent-events)

You can check all eloquent events here: )

New events are :

- `pivotSyncing`, `pivotSynced`
- `pivotAttaching`, `pivotAttached`
- `pivotDetaching`, `pivotDetached`
- `pivotUpdating`, `pivotUpdated`

The easiest way to catch events is using methods in your model's `boot()` method:

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

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

    static::pivotSynced(function ($model, $relationName, $changes) {
        //
    });

    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 catch them using dedicated Event Listeners:

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

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

[](#supported-relationships)

**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 **one** **pivotSyncing** and **one** **pivotSynced** event. Whether a row was attached/detached/updated during sync only **one** event is dispatched for all rows but in that case, you can see all the attached/detached/updated rows in the $changes variables. E.g. *How does sync work:* The sync first detaches all associations and then attaches or updates new entries one by one.

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::pivotSynced(function ($model, $relationName, $changes) {
        echo 'pivotSynced';
        echo get_class($model);
        echo $relationName;
        print_r($changes);
    });

    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 Primary Key

[](#attaching-with-primary-key)

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)

Running this code

```
$user = User::first();
$user->roles()->attach([
     1 => ['pivot_attribut' => 1],
     2 => ['pivot_attribut' => 0]
 ]);
 $user->roles()->sync([
     1 => ['pivot_attribut' => 0]
     3 => ['pivot_attribut' => 1]
 ]);
```

You will see this output

```
pivotSynced
App\Models\User
roles
[
   "attached" => [
     0 => 3
   ]
   "detached" => [
     1 => 2
   ]
   "updated" => [
     0 => 1
   ]
 ]

```

### Detaching

[](#detaching)

Running this code

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

```

You will see this output

```
pivotAttached
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']]

```

###  Health Score

66

—

FairBetter than 99% of packages

Maintenance85

Actively maintained with recent releases

Popularity54

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 59.6% 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 ~165 days

Recently: every ~268 days

Total

16

Last Release

79d ago

Major Versions

8.0 → 9.0.02022-02-09

9.0.4 → 10.0.02023-02-17

10.0.1 → 11.0.02024-03-14

11.0.0 → 12.0.02025-02-26

12.0.0 → 13.0.02026-02-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/4374bfc5d8583aa8c25c5080f1fcfaf09027822f47724ba6b64abc564945c80a?d=identicon)[mikebronner](/maintainers/mikebronner)

---

Top Contributors

[![fico7489](https://avatars.githubusercontent.com/u/4559663?v=4)](https://github.com/fico7489 "fico7489 (115 commits)")[![mikebronner](https://avatars.githubusercontent.com/u/1791050?v=4)](https://github.com/mikebronner "mikebronner (39 commits)")[![AbdelAbouhassane](https://avatars.githubusercontent.com/u/92714026?v=4)](https://github.com/AbdelAbouhassane "AbdelAbouhassane (11 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)")[![SonarSoftware](https://avatars.githubusercontent.com/u/12124408?v=4)](https://github.com/SonarSoftware "SonarSoftware (3 commits)")[![hubov](https://avatars.githubusercontent.com/u/12485926?v=4)](https://github.com/hubov "hubov (3 commits)")[![faytekin](https://avatars.githubusercontent.com/u/4013224?v=4)](https://github.com/faytekin "faytekin (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)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")[![DaniTulp](https://avatars.githubusercontent.com/u/18421761?v=4)](https://github.com/DaniTulp "DaniTulp (1 commits)")[![scybulski](https://avatars.githubusercontent.com/u/10341108?v=4)](https://github.com/scybulski "scybulski (1 commits)")

---

Tags

laravel pivot eventslaravel BelongsToMany eventseloquent extra eventslaravel sync eventseloquent events

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  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)[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)[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)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[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)
