Search code examples
laravellaravel-5eloquenteager-loading

How to eager load the nested relationship in laravel?


I have three entities User, Blog and Comments. I can load the user blog with the below code:

$userBlogs = User::with('blogs')->get();

But how can I eager load the comments related to each blog?

User:

public function blogs() {
    return $this->hasMany(Blog::class);
}

Blog:

public function comments() {
  return $this->hasMany(Comments::class);
}

Solution

  • You can do this

    $userBlogs = User::with('blogs.comments')->get();
    

    or you can

    $userBlogs  = User::with(['blogs' => function ($query) {
        $query->with('comments');
    }]