Eager Load Pivot Relations

Eager Load Pivot Relations

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.

Filed in: News

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Developer
Remote
EC Pro
Senior Full-Stack Engineer
[REMOTE: USA Only] All Other Applications Will be Rejected Immediately"
Curricula
Senior Full Stack PHP Developer
Canada
Motto Design Studio
Software Engineer
Remote, USA Only
Grow Progress
Lead Backend PHP Developer
Hamburg, Deutschland
ABOUT YOU GmbH