Search code examples
laravelpaginationrelationshipeager-loading

Laravel 5.4 - How to paginate eager loading relationships


I have the following code to retrieve a given section's threads along with its comments along with its likes. It works but I want to paginate the results.

return $this->threads()->where('state', '=', 'active')->with('comments.likes')->get();

One way is to do this, but it results in a ton of queries as it doesn't eager load.

return $this->threads()->where('state', '=', active)->paginate(5);

Is there any way I can eager load all the data and also take advantage of Laravel's pagination magic?


Solution

  • You can paginate threads like this:

    Thread::where('section_id', $sectionId)
          ->where('state', 'active')
          ->with('comments.likes')
          ->paginate(5);