Laravel Eloquent Lazy Eager Load Count

I'm ideally looking for a function like

load('relationship')

but which loads a count in the same way

withCount('relationship')

works for eager loading.

I'm thinking it is going to be called loadCount('relationship')


Solution 1:

loadCount() is available since Laravel 5.8

$post->loadCount('comments');

$post->comments_count;

Docs

Solution 2:

As of Laravel 5.2, this functionality is built-in.

Provided you have a hasMany relationship between Post and Comment, do:

<?php

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

You can even eager load relationships count by default by declaring this in your model:

<?php

// Post model

protected $withCount = ['comments'];