Courses

Laravel 12 Eloquent: Expert Level

Use withCount When Just Counting

Summary of this lesson:
- Using withCount() for relationship counting
- Implementing aggregate relationship methods
- Understanding eager loading limits
- Optimizing relationship count queries

Let's look at a scenario where you must query the related records amount. A typical example would be loading the user with projects, and you need to show the amount of projects per user.

$users = User::with('projects')->get();
 
foreach ($users as $user) {
print '<div><strong>' . $user->id . ': ' . $user->name . '</strong>: ' . $user->projects->count() . '</div>';
print '<hr />';
}

The result would look like this:

In this case, we load all the projects, which could be thousands across all users, which is not good for performance. But what if you only need the count of the projects?

In such a case, Laravel has a method withCount(). And then, instead of using relation and count, Laravel creates an attribute {relation}_count. In this example, it will be projects_count.

$users = User::withCount('projects')->get();
 
foreach ($users as $user) {
print '<div><strong>' . $user->id . ': ' . $user->name . '</strong>: ' . $user->projects_count . '</div>';
print '<hr />';
}

More Methods

In addition to the withCount() method, there are more aggregate functions withMin(), withMax(), withAvg(), withSum(), and withExists() methods. These methods will create an attribute with a name as {relation}_{function}_{column}.

$users = User::withMax('projects', 'id')->get();
 
foreach ($users as $user) {
print '<div><strong>' . $user->id . ': ' . $user->name . '</strong>: ' . $user->projects_max_id . '</div>';
print '<hr />';
}

So these helpful methods will give you much better performance than loading the entire relationship with the with() method and then using collection methods to calculate in memory.


Code for this lesson can be found on GitHub.

Previous: Methods to Query Relationship Data

No comments yet…

avatar
You can use Markdown