Laravel’s withCount() Method with Conditional Counts

Get precise counts of related data in Laravel using withCount with conditions. Ideal for dashboards, reports, and cleaner queries across all projects.

Laravel’s withCount() method lets you directly count related records including only the ones that match specific conditions like status, role or flags without loading the full data. It’s useful when you need a count of connected items but want to keep the query lightweight and precise.

Instead of manually looping through relationships, you can filter and fetch these counts in one clean query. Whether you're building dashboards, analytics or user summaries this method quietly powers smarter outputs. Stick around, because a few real-world tricks can change how you use it.

What Does withCount Do in Laravel?

Laravel’s withCount() adds a count of related records directly to your query without fetching the entire relationship.

  • Saves queries by avoiding full relationship loading
  • Adds a [relation]_count field to your result set automatically
  • Works great with hasMany or morphMany relationships
  • Useful for displaying quick counts in dashboards, APIs or summaries

Can You Add Conditions to withCount?

Yes, you can apply custom conditions inside withCount() using a closure to filter what gets counted.

  • Add logic like where('status', 'active') inside the relationship count
  • Only the matching records are included in the count
  • Keeps your queries clean and avoids unnecessary data joins

How to Count Specific Related Records Using withCount

Use a closure inside withCount() to count only the related records that match your condition, like approved or active entries.

Example 1 – Count Approved Comments for Each Article

To count only approved comments for each article, you can add a condition inside withCount():

$articles = Article::withCount([    'comments' => function ($query) {         $query->where('is_approved', true);     } ])->get();

This will return each article with a comments_count field that reflects only the approved ones. No extra queries, no full comment data just the count.

Example 2 – Count Active Orders per Customer

Here’s how to get the number of active orders for every customer:

$customers = Customer::withCount([    'orders' => function ($query) {         $query->where('status', 'active');     } ])->get();

This adds an orders_count column for each customer, only including orders marked as “active.” Perfect for summaries or dashboard views.

Filter by Relationship Count Without Repeating Patterns

You can use withCount() alongside conditional filters and having() to return only the data you care about like users with paid activity or articles buzzing with feedback.
Also Read: The Key Features of Laravel 7 Framework

Example 3 –  Articles with High Engagement (More Than 5 Comments That Are Approved)

$articles = Article::select('id', 'title')    ->withCount(['comments as approved_comments_count' => function ($q) {        $q->where('is_approved', true);     }])     ->having('approved_comments_count', '>', 5)     ->get();

This filters out low-engagement content and gives you a ready list of articles users are actively commenting on great for dashboards or content scoring.

Bonus – Customers with Active Paid Plans

$activeUsers = User::selectRaw('users.*, COUNT(subscriptions.id) as active_subs_count')    ->leftJoin('subscriptions', function ($join) {        $join->on('users.id', '=', 'subscriptions.user_id')              ->where('subscriptions.status', '=', 'paid');     })     ->groupBy('users.id')     ->having('active_subs_count', '>=', 1)     ->get();

This is useful when you want to skip free-tier users and pull only those generating revenue. The selectRaw + groupBy combo makes it flexible for more complex reports.

Real-World Tips to Use withCount Without Hurting Performance

  • Stick to what's needed: If all you're doing is counting, no need to drag in full columns. Use select() to keep things lean.
  • Make indexes your friend: Filtering on status, approved, or type? Indexed columns can speed up even large datasets.
  • Keep it readable: It’s tempting to chain multiple query filters, but too many layers make debugging a nightmare and slow things down.
  • Know when not to count: If you're only checking if something exists, skip withCount() entirely has('relation') is lighter and faster.
Did you know? 

In 2024/25, the Laravel repo on GitHub had over 80,000 stars, far surpassing Symfony (~30,000), showcasing strong developer trust and engagement

Conclusion

The withCount() method in Laravel lets you count related records directly within your queries  even with conditions without loading the entire relationship, saving both time and resources.

Used correctly, it improves query performance keeps your logic clean and gives you precise control when displaying filtered relationship data in real-time applications.

Related

CORS errors in Laravel usually pop up when your frontend tries talking to a different domain  but the right headers aren’t set. Laravel (v7 and…

10 Oct, 2025

Finding the right Laravel developers can be the difference between a scalable, secure web application and one that struggles to perform. As businesses increasingly rely…

08 Sep, 2025

Controllers act as the traffic director models handle the data layer. Knowing their roles keeps your app clean, fast and scalable  let’s simplify it further.…

02 Sep, 2025
Request a Quote Schedule a Meeting