Eloquent withCount(): Get Related Records Amount

Eloquent has one less-known function called withCount(): it helps to get the amount of related records inside of the main object. It also works with two layers deep, inside of hasManyThrough relations. Let’s take a look.

In our example mini-project, we will have three models: User, Post and Comment. All relationships can be described, looking at app/User.php model:

public function posts()
    return $this->hasMany(Post::class);

public function comments()
    return $this->hasManyThrough(Comment::class, Post::class);

Now, we will try to show this table – the list of users and the amount of their posts/comments:

To do that, here’s our UserController code:

public function index()
    $users = User::withCount(['posts', 'comments'])->get();
    return view('users', compact('users'));

Every parameter that is specified in withCount() method, becomes main object’s _count property. So in this case, we will have $user->posts_count and $user->comments_count variables.

Then, in our Blade file we have this:

<table class="table">
            <th class="text-center">Posts</th>
            <th class="text-center">Comments</th>
        @foreach ($users as $user)
                <td>{{ $user->name }}</td>
                <td class="text-center">{{ $user->posts_count }}</td>
                <td class="text-center">{{ $user->comments_count }}</td>

Notice, that withCount() works with both hasMany() relationship, and also 2nd level deep with hasManyThrough().

Another example is that we can even filter the query with withCount() relationship. Let’s say that our comments table has a column approved, and then we can filter that separately and even assign an alias to that column name:

$users = User::withCount([
    'comments as approved_comments_count' => function ($query) {
        $query->where('approved', 1);

And then we receive $user->approved_comments_count that we can use in Blade.

More examples of withCount() method – in the official Laravel documentation.

Like our articles?
Check out our Laravel online courses!


  1. Hi! Good example!

    Now, how can you show all posts information for the logged user and each post will have also included the total count of comments? The upper level should be posts but that posts must be the ones created by the logged user.


  2. hello sir,
    how can i implement with count in 3 level deep relation.
    relation. all are in hasMany relation.


Please enter your comment!
Please enter your name here