audunru / eager-load-pivot-relations
Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Package info
github.com/audunru/eager-load-pivot-relations
pkg:composer/audunru/eager-load-pivot-relations
Requires
- php: ^8.3
- illuminate/database: ^13.0
- illuminate/support: ^13.0
Requires (Dev)
- laravel/pint: ^1.0
- orchestra/testbench: ^11.0
- php-coveralls/php-coveralls: ^2.2
- phpmd/phpmd: ^2.10
- phpunit/phpunit: ^12.0
- roave/security-advisories: dev-latest
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Note: This is a fork of 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: https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a
Installation
composer require audunru/eager-load-pivot-relations
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 { } class Item extends \Eloquent { public function plans() { return $this->belongsToMany('Plan', 'plan_item'); } } use audunru\EagerLoadPivotRelations\EagerLoadPivotTrait; class Plan extends \Eloquent { // Use the trait on the model that defines the belongsToMany() relation. // Laravel calls newBelongsToMany() on this model when it creates the // Plan::items() relation, and the trait overrides that method. use EagerLoadPivotTrait; 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.
Item does not need the trait for Plan::with('items.pivot.unit'). If you also eager load pivot relations through Item::plans(), for example Item::with('plans.pivot.unit'), add the trait to Item too.
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:
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
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.
use audunru\EagerLoadPivotRelations\EagerLoadPivotTrait; class Plan extends \Eloquent { use EagerLoadPivotTrait; public function items() { return $this->belongsToMany('Item', 'plan_item') ->withPivot('unit_id', 'qty', 'price') ->using('PlanItem') ->as('planItem'); } }
The trait on Plan is sufficient, as in the example above. The package reads the pivot accessor
from the items relation, which Plan defines.
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; }
Alternative: chaperone() for back-references
Laravel 13.31.0 and later has chaperone() for BelongsToMany relations that use a custom pivot model
(laravel/framework#61152).
With chaperone(), Laravel sets the pivot relations that point back to the two models of the relation.
It uses the models that are already in memory, so it runs no extra query.
class PlanItem extends \Illuminate\Database\Eloquent\Relations\Pivot { protected $table = 'plan_item'; public function plan() { return $this->belongsTo('Plan'); } public function item() { return $this->belongsTo('Item'); } public function unit() { return $this->belongsTo('Unit'); } } class Plan extends \Eloquent { public function items() { return $this->belongsToMany('Item', 'plan_item') ->using('PlanItem') ->withPivot('unit_id', 'qty', 'price') ->chaperone(); } }
Without chaperone(), you can use this package to load the back-reference:
return Plan::with('items.pivot.item')->get();
With chaperone(), Plan::with('items') is sufficient. Each $item->pivot->plan and $item->pivot->item is already set.
You still need this package when a pivot relation points to a different model, like unit.
You can use chaperone() and this package on the same relation. Add the trait to Plan, the model that defines the items() relation:
use audunru\EagerLoadPivotRelations\EagerLoadPivotTrait; class Plan extends \Eloquent { use EagerLoadPivotTrait; }
Then Plan::with('items.pivot.unit')->get() loads unit with one query, and chaperone() sets plan and item on each pivot.
On Laravel 13.0 to 13.30, chaperone() is not available. This package works on all supported Laravel versions, also for back-references.
Other Examples and Use-cases
https://github.com/ajcastro/eager-load-pivot-relations-examples
