Eager Load Pivot Relations
Published on by Paul Redmond
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:
$plan = Plan::with('items.pivot.unit')->find($id);$plans = Plan::with('items.pivot.unit')->get(); // Load other relations as well$plans = Plan::with([ 'items.pivot.unit', 'items.pivot.unit.someRelation',])->get();
You can also customize the name of the pivot model accessor:
class Plan extends \Eloquent{ public function items() { return $this->belongsToMany('Item', 'plan_item') ->withPivot('unit_id', 'qty', 'price') ->using('PlanItem') ->as('planItem'); }} $plan = Plan::with('items.planItem.unit')->get(); foreach ($plan->items as $item) { echo $item->planItem->unit->name}
Check out the package’s readme for installation instructions and documentation. The author has an example project to demonstrate using this package.