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