DEV Community

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

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more