58

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

3 Answers 3

83

loadCount() is available since Laravel 5.8

$post->loadCount('comments'); $post->comments_count; 

Docs

Sign up to request clarification or add additional context in comments.

1 Comment

if someone's method is myMethod and trying to load the count, it should be my_method_count.
37

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

3 Comments

This is all true, however I was looking for lazy eager loading (see), i.e. being able to load a count after the model has already been retrieved.
No the accepted answer is totally right for lazy loading counts
@shigg Except that it's not lazy loading anything. The count query is performed at the same time as the main query, meaning it's being eager loaded. Which Laravel supports by default as I demonstrated above.
16

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; 

3 Comments

This is looking really good and the link you provide includes adding a custom Accessor which makes it even simpler. Just need to confirm that it works with lazy eager loading and we'll be away.
It would be better if Laravel have this function build in with Eloquent...
It does. Check my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.