thebigk's avatar
Level 13

How to paginate an eager loaded relationship?

I wish to eager load 'replies' for any thread being shown to the user. My current approach is to use route-model binding and then separately calling 'replies'.

public function(Thread $thread) {
    $replies = $thread->replies()->paginate(10);
    return view('Forum.Threads.Show', compact(['thread', 'replies']));
}

Then in my view, I simply do foreach($replies as $reply) .... {{$replies->render()}}

However, I was wondering if there's a way do it differently. Something like --

public function( $threadId ) {
    $thread = Thread::with('replies'); 
    return view('Forum.Threads.Show', compact('thread'));
}

However, I'm not sure how'd pagination work in the second case. Would really appreciate if someone can show me the right way to do this.

0 likes
3 replies
Ricardo's avatar

@thebigk in the first part, you have two queries, one for the thread, one for 10 paged answers; in the second you have two queries, one for the thread, one for all the answers.

If I were you, I would choose the first approach, with no additional work to do.

Please or to participate in this conversation.