Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

orest's avatar
Level 13

minimise queries for nested paginated data

I have the models User, ProfilePost and Comment

  • A user has many profilePosts
  • A profile post has many comments
class ProfilePost extends Model
{
	  public function comments()
    {
        return $this->morphMany(Reply::class, 'repliable');
    }
}
class User
{

    public function profilePosts()
    {
        return $this->hasMany(ProfilePost::class, 'profile_owner_id');
    }
}

When i visit a user's profile

I want to get the paginated profile posts of that user

And for each post I want to get the paginated comments

I have come up with the following solution

class ProfileController 
{
	 public function show(User $user)
    {
       
        $profilePosts = $user->profilePosts()
            ->latest()
            ->paginate(ProfilePost::PER_PAGE);

        foreach ($profilePosts->items() as $post) {
            $post->append('paginatedComments');
        }

	return view('profiles.show', compact('user', 'profilePosts'));
}
class ProfilePost extends Model
{
	 public function getPaginatedCommentsAttribute()
    {
        return $this->comments()
            ->withLikes()
            ->latest()
            ->paginate(ProfilePost::REPLIES_PER_PAGE);
    }
}

The issue here is that for every profile post there will be a new query to get the comments for that post

Is there way to minimise the number of queries ?

0 likes
3 replies
gitwithravish's avatar

It will not work like that. He needs pagination on comments for each post. You cannot achieve that in one query. @chaudigv

1 like
gitwithravish's avatar

This looks fine to me. You have to make separate requests for comment if you want to paginate them.

If performance is your concern then two points to keep in mind

  • Load fewer posts and load more as user changes the page or scrolls down. For example if you just load 5 posts then there will be only 6 queries
  • If you index your tables properly, the queries won't feel slow
  • You can also keep a button. If user presses that button then only load the comments.

In short, If your requirement is such then I don't think you should break your head in finding a better implementation for it. You are doing good

1 like

Please or to participate in this conversation.