So many examples of this already have you honestly tried to search for I have three tables. https://laracasts.com/discuss?q=Three+tables
User - Post - Likes to a post by user
Hello, I have 3 models - User, Post and PostLike . So, a User can create many posts, and each post can be liked by users. I', trying to get a user to like a particular post, and the be able to display all the users who have liked a particular post.
User Model :
public function posts()
{
return $this->hasMany(Post::class);
}
public function post_like()
{
return $this->hasMany(PostLike::class);
}
Post Model :
public function user()
{
return $this->belongsTo(User::class);
}
public function post_like()
{
return $this->hasMany(PostLike::class);
}
PostLike Model :
public function post()
{
$this->belongsTo(Post::class);
}
public function user()
{
$this->belongsTo(User::class);
}
The Post Controller, where i display a list of all my posts :
public function index()
{
$all_posts = Post::all();
return view('wall', compact('all_posts'));
}
Now, i try to display the posts, it's likes, and the users who have liked it :
@if(count($all_posts))
@foreach($all_posts as $post)
<div>
<ul>{{ $post->body }} - by {{ $post->user->name }} | Likes = {{ count($post->post_like) }}
| Liked by = {{ $post->post_like->user->name}} // This is throwing errors
<form action="/like-post" method="POST">
{{ csrf_field() }}
<input type="hidden" name="likeThePost" value={{ $post->id or '' }} />
<button class="btn btn-primary" type="submit" value="Submit">Like</button>
</form>
</ul>
</div>
@endforeach
@endif
</div>
Please check my comment "This is throwing errors" above. I'd appreciate if someone can point me to the right direction.
Thanks.
dump($post->post_like);
should return a collection of PostLike instances, even if it just contains a single model. You need to iterate over that collection to get each PostLike's user.
@foreach($all_posts as $post)
{{ $post->body }} - by {{ $post->user->name }} | Likes = {{ count($post->post_like) }}
@foreach($post->post_like as $like)
| Liked by {{ $like->user->name }}
@endforeach
@endforeach
Regarding the nested eager loading:
Post::with(['user', 'post_like.user'])
retrieves the posts including the post's users and the post's likes including the users who liked the post.
Seriously, don't worry about this until you get the other stuff sorted out even though it is important :-)
Please or to participate in this conversation.