Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Use withCount When Just Counting

Premium
1:37

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…