Courses

Laravel 11 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...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord