Eager Load Pivot Relations

News

October 2nd, 2020

laravel-database-hashing.png

Arjon Jason Castro created a package for eager-loading pivot relations (BelongsToMany), which can help avoid N+1 queries on the pivot model.

Once you’re model has the EagerLoadPivotTrait you can eager load them as follows:

1$plan = Plan::with('items.pivot.unit')->find($id);
2$plans = Plan::with('items.pivot.unit')->get();
3 
4// Load other relations as well
5$plans = Plan::with([
6 'items.pivot.unit',
7 'items.pivot.unit.someRelation',
8])->get();

You can also customize the name of the pivot model accessor:

1class Plan extends \Eloquent
2{
3 public function items()
4 {
5 return $this->belongsToMany('Item', 'plan_item')
6 ->withPivot('unit_id', 'qty', 'price')
7 ->using('PlanItem')
8 ->as('planItem');
9 }
10}
11 
12$plan = Plan::with('items.planItem.unit')->get();
13 
14foreach ($plan->items as $item) {
15 echo $item->planItem->unit->name
16}

Check out the package’s readme for installation instructions and documentation. The author has an example project to demonstrate using this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.