News

Eager Load Pivot Relations

Published
Eager Load Pivot Relations image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article