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

Čamo's avatar
Level 3

How to make efficient query for $post->commnets and comment->user

Hello, I have a Post model which hasMany Commnets and every comment has one User. If I run this blade code

@foreach( $post->comments as $comment )
      <div>{{ $comment->text }} <br><small>{{ $comment->user->name }}</small></div>
@endforeach

it makes one separate query for user in every loop of the foreach cycle.

I know about Post::with() but this is the third level of relations. Is it possible to have only one query for all users which wrote comments?

Controller code looks like

public function detail(Post $post)
{
	return view('home.detail')->with([
		'post' => $post
	]);
}
0 likes
4 replies
squiaios's avatar

Your $post variable is already loaded, so if you can use the load method

public function detail(Post $post)
{
        $post->load(['comments', 'comments.user']);

	return view('home.detail')->with([
		'post' => $post
	]);
}
1 like
Čamo's avatar
Level 3

This is it. Thank you Mišo.

1 like

Please or to participate in this conversation.