Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user like for each post

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!

like image 816
user4986516 Avatar asked Jan 18 '26 15:01

user4986516


1 Answers

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();
like image 122
Alexey Mezenin Avatar answered Jan 20 '26 14:01

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!