PHPackages                             ajcastro/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. [Database &amp; ORM](/categories/database)
4. /
5. ajcastro/eager-load-pivot-relations

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

ajcastro/eager-load-pivot-relations
===================================

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

v0.3.0(3y ago)2451.7M—7.2%22[8 issues](https://github.com/ajcastro/eager-load-pivot-relations/issues)4MITPHPPHP &gt;=5.6.0

Since Apr 23Pushed 2y ago6 watchersCompare

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

READMEChangelog (5)Dependencies (4)Versions (6)Used By (4)

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

40

—

FairBetter than 88% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity59

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 53.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 ~322 days

Total

5

Last Release

1294d ago

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

v0.2.1PHP &gt;=5.6.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4918318?v=4)[Arjon Jason Castro](/maintainers/ajcastro)[@ajcastro](https://github.com/ajcastro)

---

Top Contributors

[![ajcastro](https://avatars.githubusercontent.com/u/4918318?v=4)](https://github.com/ajcastro "ajcastro (8 commits)")[![SuperDJ](https://avatars.githubusercontent.com/u/6484766?v=4)](https://github.com/SuperDJ "SuperDJ (5 commits)")[![jasonlewis](https://avatars.githubusercontent.com/u/829059?v=4)](https://github.com/jasonlewis "jasonlewis (1 commits)")[![nrayann](https://avatars.githubusercontent.com/u/5538985?v=4)](https://github.com/nrayann "nrayann (1 commits)")

---

Tags

eager-loadingeloquentlaravelmodelpivotrelations

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

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