Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Fetch count of records for children relationships in Laravel Eloquent

There comes a time when you want to fetch the number of records for a child relationship along with the main Eloquent query.

For instance, let’s say, I want to get the number of books and publications when fetching authors. To do so, we can use withCount method on the Eloquent model like so.

$authors = app\Author::withCount(['books', 'publications'])->get();

Now, when looping over this, we can get the count for these child relationship records by using a {relation}_count column on the iteration instance like so.

foreach ($authors as $author) {
    $totalBooks = $author->books_count;

    $totalPublications = $author->publications_count;
}

You can use alias (using as) and Closures to utilize the same relationship twice in withCount for different constraints like so.

$authors = app\Author::withCount([
    'books', 
    'books as published_books_count' => function (Builder $query) {
        $query->where('status', 'published');
    }
])->get();

The aliased count column can be accessed like so.

$author->published_books_count;

You can learn more about this feature here.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?