Skip to main content
Category:

Laravel Eloquent Lazy Eager Load Count

 

You can use withCount() like this:

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

 

also you can use loadCount(): loadCount() is available since Laravel 5.8

$post->loadCount('comments');

$post_id = $post->id

$comments_count = $post->comments_count;

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook