Laravel `loadCount` Relationship Count 😎

Mahfuzur Rahman - Dec 26 '23 - - Dev Community

Hello Artisans 😎

Did you know you can get relationship counts even after retrieving the parent model? πŸ€”

Using the loadCount method, you may load a relationship count after the parent model has already been retrieved:

$book = Book::first();

$book->loadCount('genres');
Enter fullscreen mode Exit fullscreen mode

If you need to set additional query constraints on the count query, you may pass an array keyed by the relationships you wish to count. The array values should be closures which receive the query builder instance:

$book->loadCount(['reviews' => function (Builder $query) {
    $query->where('rating', 5);
}])
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . .
Terabox Video Player