Laravel withCount elements in related and subrealted table.

Updated: Feb 09, 2025

Laravel withCount elements in related and subrealted table.

In Laravel, the withCount method is used to eager load the relationship and count the number of related records at the same time. This can be particularly useful when dealing with complex queries involving multiple tables and relationships.

Let's consider an example where we have two tables, posts and comments. Each post can have multiple comments. We want to retrieve all posts along with the number of comments for each post.

First, we need to define the relationships in our models. In Post.php:

public function comments()
{
    return $this->hasMany(Comment::class);
}

And in Comment.php:

public function post()
{
    return $this->belongsTo(Post::class);
}

Now, we can use the withCount method in our controller to retrieve all posts with the number of comments for each post:

$posts = Post::withCount('comments')->get();

return view('posts.index', ['posts' => $posts]);

In the view, we can access the number of comments for each post using the $post->comments_count property:

@foreach ($posts as $post)
    <div>
        {{ $post->title }}
        <p>{{ $post->body }}</p>
        <p>{{ $post->comments_count }} comments</p>
    </div>
@endforeach

But what if we have sub-relationships? For example, each comment can have multiple replies. We can use nested withCount methods to eager load the relationships and count the related records:

$posts = Post::with(['comments' => function ($query) {
    $query->withCount('replies');
}])->get();

return view('posts.index', ['posts' => $posts]);

In the view, we can access the number of comments and replies for each post using the following properties:

@foreach ($posts as $post)
    <div>
        {{ $post->title }}
        <p>{{ $post->body }}</p>
        <p>{{ $post->comments_count }} comments</p>
        <p>{{ $post->comments->sum('replies_count') }} total replies</p>
    </div>
@endforeach

In summary, Laravel's withCount method is a powerful tool for eager loading relationships and counting related records. It can be used with multiple relationships, including sub-relationships, to build complex queries efficiently.