Use eager loading with with(). Checkout Optimize Laravel Eloquent Queries with Eager Loading.
Apr 24, 2021
3
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 ?
Please or to participate in this conversation.