The withCount
method in Laravel's Eloquent ORM allows you to retrieve the count of related records for a given model. Here is how you can use it:
// User.php
public function posts()
{
return $this->hasMany(Post::class);
}
withCount
method.$users = User::withCount('posts')->get();
The above code will retrieve all users along with the count of their related posts.
_count
.foreach ($users as $user) {
echo $user->posts_count;
}
In the above example, $user->posts_count
will give you the count of posts associated with that user.
You can also use the withCount
method with additional query constraints and eager loading:
$users = User::withCount(['posts' => function ($query) {
$query->where('is_published', true);
}])
->with('posts')
->get();
In the above example, the withCount
method is used with a closure to add additional constraints to the count query. The with
method is then used to eager load the related posts
while retrieving the users.