Search code examples
phplaravel

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

  • 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;