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