DEV Community

Cover image for Laravel Nested Eager Loading on Polymorphic Relationships
Muath Alsowadi
Muath Alsowadi

Posted on • Originally published at muathye.com

6 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
pepperfm profile image
Dmitry

i spend a lot of time for find this solution. and finally im here. thank you!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay