'Nested Eager Loading count

I need to get the contacts count of each author

$books = Book::with('author.contacts')->get();

The following attempt doesn't work

$books = Book::with('author.contacts')
             ->whithCount('author.contacts')
             ->get();


Solution 1:[1]

You can try something like this, where you use a function to get the count.

Book::with(['author' => function($query){
   $query->withCount('contacts');
}])->get();

You can access likes count by author->contracts_count;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dz0nika