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.
Laravel’s withCount() adds a count of related records directly to your query without fetching the entire relationship.
Yes, you can apply custom conditions inside withCount() using a closure to filter what gets counted.
To count only approved comments for each article, you can add a condition inside withCount():
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.
Here’s how to get the number of active orders for every customer:
This adds an orders_count column for each customer, only including orders marked as “active.” Perfect for summaries or dashboard views.
Also Read: The Key Features of Laravel 7 Framework
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.
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.
“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
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.
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingCORS 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…
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…
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.…
Let’s discuss how our dedicated experts can help.