Load Count on-the-fly

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}]);

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord