Append relationship count with each model in Eloquent

Viewed 295

in my app an address can have many places, now I want to retrieve all address with the count of places appended to EACH address, how can I do this with Eloquent?

$address= Address::with('places')->get();

Thanks in davance

2 Answers

Use Eloquent's withCount():

$address = Address::withCount('places')->get();

It will return the count of each model's related rows with a field

$address->places_count

Official documenation for withCount can be found here

You can use withCount method, which will place a {relation}_count column on your resulting models.

$addresses = App\Models\Address::withCount('places')->get();

then get the count of places by {relation}_count.

foreach ($addresses as $address) {
  echo $address->places_count;
}
Related