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
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 (Drupal & Laravel)

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

Web Posts

Search

Page Facebook