PHPackages                             igunultas/eager-load-pivot-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. igunultas/eager-load-pivot-relations

ActiveLibrary

igunultas/eager-load-pivot-relations
====================================

Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.

v0.2.2(6y ago)08MITPHPPHP &gt;=5.6.0

Since Apr 23Pushed 6y agoCompare

[ Source](https://github.com/igunultas/eager-load-pivot-relations)[ Packagist](https://packagist.org/packages/igunultas/eager-load-pivot-relations)[ RSS](/packages/igunultas-eager-load-pivot-relations/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (1)DependenciesVersions (5)Used By (0)

Laravel Eloquent: Eager Load Pivot Relations
============================================

[](#laravel-eloquent-eager-load-pivot-relations)

Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Medium Story:

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

[](#installation)

```
composer require ajcastro/eager-load-pivot-relations

```

Usage and Example
-----------------

[](#usage-and-example)

There are use-cases where in a pivot model has relations to be eager loaded. Example, in a procurement system, we have the following:

**Tables**

```
items
 - id
 - name

units
 - id
 - name (pc, box, etc...)

plans (annual procurement plan)
 - id

plan_item (pivot for plans and items)
 - id
 - plan_id
 - item_id
 - unit_id

```

**Models**

```
class Unit extends \Eloquent {
}

use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Item extends \Eloquent
{
    // Use the trait here to override eloquent builder.
    // It is used in this model because it is the relation model defined in
    // Plan::items() relation.
    use EagerLoadPivotTrait;

    public function plans()
    {
        return $this->belongsToMany('Plan', 'plan_item');
    }
}

class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->using('PlanItem')
            // make sure to include the necessary foreign key in this case the `unit_id`
            ->withPivot('unit_id', 'qty', 'price');
    }
}

// Pivot model
class PlanItem extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    protected $table = 'plan_item';

    public function unit()
    {
        return $this->belongsTo('Unit');
    }
}
```

From the code above, `plans` and `items` has `Many-to-Many` relationship. Each item in a plan has a selected `unit`, unit of measurement. It also possible for other scenario that the pivot model will have other many relations.

Eager Loading Pivot Relations
-----------------------------

[](#eager-loading-pivot-relations)

Use keyword `pivot` in eager loading pivot models. So from the example above, the pivot model `PlanItem` can eager load the `unit` relation by doing this:

```
return Plan::with('items.pivot.unit')->get();

```

The resulting data structure will be:

[![image](https://cloud.githubusercontent.com/assets/4918318/17958278/0d3c962a-6acb-11e6-8415-c48d01457cd6.png)](https://cloud.githubusercontent.com/assets/4918318/17958278/0d3c962a-6acb-11e6-8415-c48d01457cd6.png)

You may also access other relations for example:

```
return Plan::with([
  'items.pivot.unit',
  'items.pivot.unit.someRelation',
  'items.pivot.anotherRelation',
  // It is also possible to eager load nested pivot models
  'items.pivot.unit.someBelongsToManyRelation.pivot.anotherRelationFromAnotherPivot',
])->get();

```

Custom Pivot Accessor
---------------------

[](#custom-pivot-accessor)

You can customize the **"pivot accessor"**, so instead of using the keyword `pivot`, we can declare it as `planItem`. Just chain the `as()` method in the definition of the `BelongsToMany` relation.

```
class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->withPivot('unit_id', 'qty', 'price')
            ->using('PlanItem')
            ->as('planItem');
    }
}
```

Make sure we also use the trait to our main model which is the `Plan` model, because the package needs to acess the belongsToMany relation (`items` relation) to recognize the used pivot acessor.

```
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;

class Plan extends \Eloquent
{
    use EagerLoadPivotTrait;
}
```

So instead of using `pivot`, we can eager load it by defined pivot accessor `planItem`.

```
return Plan::with('items.planItem.unit')->get();
```

```
$plan = Plan::with('items.planItem.unit');

foreach ($plan->items as $item) {
    $unit = $item->planItem->unit;
    echo $unit->name;
}
```

Other Examples and Use-cases
----------------------------

[](#other-examples-and-use-cases)

###  Health Score

22

—

LowBetter than 23% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

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

4

Last Release

2478d ago

PHP version history (2 changes)v0.1.0PHP &gt;=5.4.0

v0.2.1PHP &gt;=5.6.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/aa4ca2e638770b222bb4c015ee9392cd4e537c7dc12b52796c5bb52fd43a57e5?d=identicon)[igunultas](/maintainers/igunultas)

---

Top Contributors

[![ajcastro](https://avatars.githubusercontent.com/u/4918318?v=4)](https://github.com/ajcastro "ajcastro (5 commits)")[![igunultas](https://avatars.githubusercontent.com/u/6320298?v=4)](https://github.com/igunultas "igunultas (1 commits)")[![jasonlewis](https://avatars.githubusercontent.com/u/829059?v=4)](https://github.com/jasonlewis "jasonlewis (1 commits)")

### Embed Badge

![Health badge](/badges/igunultas-eager-load-pivot-relations/health.svg)

```
[![Health](https://phpackages.com/badges/igunultas-eager-load-pivot-relations/health.svg)](https://phpackages.com/packages/igunultas-eager-load-pivot-relations)
```

PHPackages © 2026

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