ItSolutionStuff.com

Laravel Relationship Eager Loading with Count Example

By Hardik Savani • April 16, 2024
Laravel

Eager Loading is a concept of laravel relationship and it is a best. But when you are working with model relationship with eager loading then you require to get count number of records for relation model. At that we can use withcount() for eager loading count in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.

Whenever you require to count rows of relation model then we will use withcount(). So that can help us. you can see bellow example. i will count number of comments for each posts. you can see bellow example.

Let's see bellow example. So might be it can help you.

Simple Count Example:

$posts = Post::withCount('comments')->get();

// comments_count

Multiple Counts Example:

$posts = Post::withCount([

'comments',

'tags'

])->get();

// comments_count

// tags_count

Count with Condition Example:

$posts = Post::withCount([

'comments',

'comments as active_comments' => function (Builder $query) {

$query->where('approved', 1);

}

])->get();

// comments_count

// active_comments

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent Select Single Column to Array Example

Read Now →

Laravel Eloquent Group By Year with Sum Example

Read Now →

Laravel Eloquent When Condition Example

Read Now →

Laravel Eloquent Sum Multiple Columns Example

Read Now →

Laravel Eloquent updateOrCreate Example

Read Now →

Laravel Eloquent whereBetween() Query Example

Read Now →

Laravel Eloquent selectRaw() Query Example

Read Now →

Laravel Relationship Eager Loading Example

Read Now →

Laravel Eloquent Relationships Tutorial From Scratch

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Polymorphic Relationship Tutorial

Read Now →