Counting Related Records Dynamically with loadCount()
Laravel provides an easy way to count related records dynamically on-the-fly using loadCount(). Unlike withCount(), which loads counts when fetching the model, loadCount() allows you to fetch the count later as needed—helping with performance optimization!
Example: Counting Active Orders
Imagine an E-commerce application where a User has many Orders. Instead of always loading order counts, we can retrieve them only when needed, like this:
$user = User::find(1);
$user->loadCount('orders');
// Access the count dynamically
echo "Total Orders: " . $user->orders_count;
Adding Conditions: Count Only Active Orders
What if we only want to count orders with status = 'active'? We can filter it like this:
$user->loadCount(['orders' => function ($query) {
$query->where('status', 'active');
}]);
echo "Active Orders: " . $user->orders_count;
Bonus: You can also use multiple conditions! For example, count active orders placed in the last 30 days:
$user->loadCount(['orders' => function ($query) {
$query->where('status', 'active')->where('created_at', '>=', now()->subDays(30));
}]);
Have you used loadCount() in your Laravel projects? Drop a comment and share your experience! ??
Quality Analyst
1 个月Insightful