Edward Louth
Edward Louth

Reputation: 1060

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

Upvotes: 58

Views: 32350

Answers (3)

hubrik
hubrik

Reputation: 1019

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;

Upvotes: 16

Maksim Ivanov
Maksim Ivanov

Reputation: 4331

loadCount() is available since Laravel 5.8

$post->loadCount('comments');

$post->comments_count;

Docs

Upvotes: 83

rzb
rzb

Reputation: 2153

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

Upvotes: 37

Related Questions