Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Abhimanev's avatar

Get Total count of the related table

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

0 likes
2 replies
fahadkhan1740's avatar

try this

Like::with('post' => function($query) {
    $query->where('user_id', $userId);
})->sum();
Abhimanev's avatar
Abhimanev
OP
Best Answer
Level 1

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.