Reputation: 1
I'm new to laravel and I'm still trying to learn.
This my code in my controller:
public function index(User $user){
$posts = $user->posts()->with(['user', 'likes']);
return view('users.posts.index', [
'user' => $user,
'posts' => $posts,
]);
}
And this is the code on blade.php
{{$user->name}}
I've also tried checking if the code:
dd($posts = $user->posts()->with(['user', 'likes']));
and it seems fine since it's returning data from the database. With these codes it was supposed to show the User's Post on a different page when you click on the User's name. The problem is that it only shows the user's name but not the user's post. I'm only following a tutorial but the result was different with the tutorial and the one that I'm doing. Can someone please help?
Upvotes: 0
Views: 372
Reputation: 50541
I suppose you are trying to lazy eager load the posts
relationship on this $user
and load the user
and likes
relationship for those posts. You can try to use load
to load these relationships on the Collection:
$posts = $user->posts->load('user', 'likes');
Or load
on the User instance:
$user->load('posts.user', 'posts.likes');
$posts = $user->posts;
If you are not trying to have these relationships loaded on the $user
but you just want the posts with their relationships you can eager load them off of the relationship itself:
$posts = $user->posts()->with('user', 'likes')->get();
Upvotes: 1