Laravel Eloquent Lazy Eager Load Count

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'];

loadCount() is available since Laravel 5.8

$post->loadCount('comments');

$post->comments_count;

Docs


This solution works great for me:

Create a new hasOne relationship on the related model and add a raw select to the query for the count. For example, if you want to eager load the number of tasks for a given user, add this to the User Model:

public function taskCount()
{
    return $this->hasOne('App\Task')
    ->selectRaw('user_id, count(*) as count)
    ->groupBy('user_id');
}

And then eager load the count like this:

$user = User::where('email', $email)->with('taskCount')->first();

And access the count like this:

$taskCount = $user->task_count->count;