In addition to Eloquent's withCount()
method to count related records, you can also load the count on-the-fly, with loadCount()
:
1// if your Book hasMany Reviews... 2$book = App\Book::first(); 3 4$book->loadCount('reviews'); 5// Then you get access to $book->reviews_count; 6 7// Or even with extra condition 8$book->loadCount(['reviews' => function ($query) { 9 $query->where('rating', 5);10}]);