DanVeira
DanVeira

Reputation: 371

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?

Upvotes: 3

Views: 6136

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

You can paginate threads like this:

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

Upvotes: 5

Related Questions