Laravel Nested Eager Loading on Polymorphic Relationships

muathye

Muath Alsowadi

Posted on February 13, 2023

Laravel Nested Eager Loading on Polymorphic Relationships

Laravel Nested Eager Loading on Polymorphic Relationships

Sometimes you need to eager load different relationships depending on the type of model on a polymorphic relationship.

tip

For example: you have two type of users seller and buyer, the eager load relationship for seller is the product and the eager load relationship for buyer is the order.

  • First setup the Models.


class Seller extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}


Enter fullscreen mode Exit fullscreen mode


class Buyer extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}


Enter fullscreen mode Exit fullscreen mode


class Profile extends Model
{
    public function user()
    {
        return $this->morphTo();
    }
}


Enter fullscreen mode Exit fullscreen mode
  • Then load the relations like the following:


Profile:with('user', function (MorphTo $morphTo) {
    // Eager load the products for seller.
    // Eager load the orders for buyer 👇
    $morphTo->morphWith([
        Seller::class => ['products'],
        Buyer::class => ['orders'],
    ]);
})->get();


Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
muathye
Muath Alsowadi

Posted on February 13, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related