Support the ongoing development of Laravel.io →
posted 11 years ago
Eloquent

Hi,

I have 3 models:

User Post Comment

Comment belongs to a user and a post. A user has many posts as well as many comments. A post belongs to a user and has many comments. This is how eloquent relationships are created.

Now, I have a question. How can I use Laravel eager loading query in order to get the posts with comments from a certain user.

For instance, I want to have all the posts of user with ID 1 and I want to eager load all the comments on those posts.

Thank you!

Last updated 3 years ago.
0

Hi, bakinalgiev

Assuming you don't have a pivot table and the user's id is referenced in your Posts-table, this should work;

$posts = Posts::with('comments')->where('uid', '=', 1)->get();
var_dump($posts->comments);

There are lots of useful method's in Eloquent for dealing with relationships, so read through the documentation.

Last updated 3 years ago.
0

I read a bit in the documentation and this is what I got right now:

{
	$user = User::where('username', '=', $username)->firstOrFail();

	$posts = User::find($user->id)->posts()->with('comments')->get();

	return View::make('profiles.index')->with(array(
		'user' => $user,
		'posts' => $posts
	));
}

Is this clean enough, or is there another more efficient way to query?

Last updated 3 years ago.
0

This works, but you can shorten it a bit.

{
    $user = User::where('username', '=', $username)->with('posts', 'posts.comments')->get();

    return View::make('profiles.index', ['user' => $user, 'posts' => $user->posts]);
}
Last updated 3 years ago.
0

ChrisRM said:

This works, but you can shorten it a bit.

{
   $user = User::where('username', '=', $username)->with('posts', 'posts.comments')->get();

   return View::make('profiles.index', ['user' => $user, 'posts' => $user->posts]);
}

For some reason I'm getting this error http://i.gyazo.com/a437244a34ebf58b6338249bd49b982b.png

But the user->posts is set when I return my $user.

Any idea how I can fix this?

Thanks for your help so far :)

EDIT: I fixed it. Should have been ->first() instead of ->get(). Stuff works now.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.