X-Coder264's avatar

Pagination with lazy (eager) loading

I don't know how to implement pagination on a project (I'm doing a forum). I have ForumThread, ForumPost and User models. What I have so far is this:

class ForumThread extends Model
{
   /**
     * Get all posts of a thread.
     */
    public function posts()
    {
        return $this->hasMany(ForumPost::class, 'thread_id', 'id');
    }
}
class ForumPost extends Model
{
    /**
     * Get the author of the post.
     */
    public function author()
    {
        return $this->belongsTo(User::class, 'author_user_id')->select(['id','name', 'number_of_posts']);
    }

The route is:

Route::get('/forum/thread/{thread}', 'ForumController@showThread');

and the controller function is:

public function showThread(ForumThread $thread)
    {
        $ThreadInfo = $thread->load('posts.author');
        return view('forum.thread.show', ["thread" => $ThreadInfo]);
    }

Everything works with this code (I get all the posts in the thread and all the author user info I need for each post), but I don't know how to implement pagination with this code (for example to show only 20 posts per page in a thread). If I try something like

$postsPaginated = $thread->posts()->paginate(20);

I, of course, lose all the data about the user who wrote the post... I googled a lot about this and I haven't found a solution yet (on one of the many pages I found about this problem I even read that pagination isn't possible with lazy eager loading...). So any help, ideas or suggestions about how can I solve this problem are really appreciated. Thank you.

0 likes
0 replies

Please or to participate in this conversation.