Level 8
try this
Like::with('post' => function($query) {
$query->where('user_id', $userId);
})->sum();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi friends,
i have three table users,postsand likes. user is related to posts table and likes table. Now i want to get the total number of likes on the users all posts.
users
id
name
[...]
posts
id
user_id
[....]
likes
id
post_id
[...]
I hope you understood my words.
Thanks & regards Abhi Singh
Problem solved with hasManyThrought relation
public function likes()
{
return $this->hasManyThrough(LIke::class, Post::class);
}
get like counts with
$user->likes->count()
Please or to participate in this conversation.