I have a feature that lets users "like" a post (similar to Facebook). When I retrieve a post (or multiple posts), I need to include data in that query about whether or not the user liked that post.
In my Post.php model, I have the following relationship:
public function likes()
{
return $this->hasMany('App\Like');
}
Now, obviously, if I do the following query, it will retrieve all likes from all users, and not just the user logged in:
$posts = Post::with('likes')
->get();
So my question is, how can I create a relationship (maybe called userLike()) that would first check if the user is logged in, and then retrieve the like record for each post?
Thanks!
I assume that likes tables has user_id. In this case, you can use eager loading constraint like this:
$posts = Post::with([['likes' => function ($q) {
$q->where('user_id', auth()->id());
}])->get();
Alternatively, you could create a relationship with where clause:
public function userLikes()
{
return $this->hasMany(Like::class)->where('user_id', auth()->id());
}
And then use it:
Post::with('userLikes')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With