Load Relationship Counts Efficiently in Laravel Using loadCount()
Most developers use:
$post = Post::withCount('comments')->first();
This works great during initial query.
But what if the model is already loaded?
The Better Solution: loadCount()
Laravel allows you to load counts later without fetching the model again.
Basic Usage
$post = Post::find(1);
$post->loadCount('comments');
Now:
$post->comments_count
is available instantly.
Multiple Relationship Counts
$user->loadCount([
'orders',
'reviews',
]);
Real Project Example
$product = Product::find($id);
$product->loadCount([
'reviews',
'orders',
]);
Perfect for:
- Admin dashboards
- Analytics cards
- API statistics
Conditional Counts
$user->loadCount([
'orders as completed_orders_count' => function ($q) {
$q->where('status', 'completed');
}
]);
Why This Is Useful
It helps you:
- Avoid re-fetching models
- Add counts dynamically
- Keep queries optimized
- Build cleaner APIs
When to Use It
Use loadCount() when:
- Model is already loaded
- Adding stats dynamically
- Building dashboards or APIs