n Laravel Eloquent Lazy Eager Load Count | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Laravel Eloquent Lazy Eager Load Count


You can use withCount() like this:


$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:


// Post model

protected $withCount = ['comments'];


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


$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


Page Facebook