In addition to Eloquent's withCount() method to count related records, you can also load the count on-the-fly, with loadCount():
// if your Book hasMany Reviews...$book = Book::first(); $book->loadCount('reviews');// Then you get access to $book->reviews_count; // Or even with extra condition$book->loadCount(['reviews' => function ($query) { $query->where('rating', 5);}]);
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
[NEW] Laravel 13 Starter Kit Teams and Customizations
10 lessons
33 min
[FREE] Laravel 13 for Beginners: 3 Demo Projects
5 lessons
29 min
Laravel AI SDK: 6 Practical Examples
9 lessons
1 h 02 min