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([

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')

$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


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

Laravel News Partners

Laravel Jobs

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