DEV Community

Cover image for Laravel `loadCount` Relationship Count 😎
Mahfuzur Rahman
Mahfuzur Rahman

Posted on

Laravel `loadCount` Relationship Count 😎

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

Top comments (0)