Laravel Eager Loading with Count Relationship Example

Laravel Eager Loading with Count Relationship Example

In this post we will give you information about Laravel Eager Loading with Count Relationship Example. Hear we will give you detail about Laravel Eager Loading with Count Relationship ExampleAnd how to use it also give you demo for it if it is necessary.

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 5.8.

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:

Also see:Laravel Eager Loading Tutorial

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

Hope this code and post will helped you for implement Laravel Eager Loading with Count Relationship Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  39  =  40

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US