How to use Eloquent's "withCount" method to retrieve related record counts in Laravel?

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:

  1. Define a relationship between two models in Laravel's Eloquent models.
// User.php public function posts() { return $this->hasMany(Post::class); }
  1. Retrieve the related record counts using the withCount method.
$users = User::withCount('posts')->get();

The above code will retrieve all users along with the count of their related posts.

  1. Access the related record count using the defined relationship method name suffixed with _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.