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

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

audunru/eager-load-pivot-relations
==================================

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

v6.0.0(1mo ago)952.9k↓14.9%1MITPHPPHP ^8.3CI passing

Since Jan 12Pushed 1mo agoCompare

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

READMEChangelog (10)Dependencies (16)Versions (19)Used By (0)

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

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

[![Build Status](https://github.com/audunru/eager-load-pivot-relations/actions/workflows/validate.yml/badge.svg)](https://github.com/audunru/eager-load-pivot-relations/actions/workflows/validate.yml)[![Coverage Status](https://camo.githubusercontent.com/9c29149c42de10304c35ba1b56f033c1f1600954beb9da8ae67a2bc43149426e/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f617564756e72752f65616765722d6c6f61642d7069766f742d72656c6174696f6e732f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/audunru/eager-load-pivot-relations?branch=main)

Note: This is a fork of [ajcastro/eager-load-pivot-relations](https://github.com/ajcastro/eager-load-pivot-relations) with support for Laravel 8 and above, also coded by ajcastro. Many thanks to the original author for this package and his work.

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

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

[](#installation)

```
composer require audunru/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 audunru\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 audunru\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

55

—

FairBetter than 98% of packages

Maintenance89

Actively maintained with recent releases

Popularity36

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~67 days

Recently: every ~32 days

Total

13

Last Release

55d ago

Major Versions

v2.0.1 → v3.0.02024-04-07

v3.0.2 → v4.0.02025-03-16

v4.0.2 → v13.x-dev2026-03-24

v4.1.0 → v5.0.02026-03-24

v5.0.0 → v6.0.02026-03-24

PHP version history (4 changes)v1.0.0PHP &gt;=7.3.0

v2.0.0PHP ^8.1

v3.0.0PHP ^8.2

v13.x-devPHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/444043228e007e4f695d18a30380b811fb60077138f7c46f111f45a1b98e2f1c?d=identicon)[audunru](/maintainers/audunru)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (32 commits)")[![audunru](https://avatars.githubusercontent.com/u/5163790?v=4)](https://github.com/audunru "audunru (27 commits)")[![ajcastro](https://avatars.githubusercontent.com/u/4918318?v=4)](https://github.com/ajcastro "ajcastro (8 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (7 commits)")[![audunrunhn](https://avatars.githubusercontent.com/u/161304732?v=4)](https://github.com/audunrunhn "audunrunhn (6 commits)")[![SuperDJ](https://avatars.githubusercontent.com/u/6484766?v=4)](https://github.com/SuperDJ "SuperDJ (5 commits)")[![semantic-release-bot](https://avatars.githubusercontent.com/u/32174276?v=4)](https://github.com/semantic-release-bot "semantic-release-bot (4 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

laraveldatabaseeloquent

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)[czim/laravel-filter

Filter for Laravel Eloquent queries, with support for modular filter building

8973.0k3](/packages/czim-laravel-filter)[eusonlito/laravel-database-cache

Cache Database Query results on Laravel Query Builder or Eloquent

194.2k](/packages/eusonlito-laravel-database-cache)

PHPackages © 2026

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