Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 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 2 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 2 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 2 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 2 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.

© 2024 Laravel.io - All rights reserved.