In this quick example, let's see laravel eloquent count eager loading. This article will give you simple example of get record with count laravel relation. step by step explain laravel withcount. if you want to see example of eager loading count laravel then you are a right place. Let's see bellow example laravel relationship count.
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...
Do you like below Tutorials ?
- Angular Json Pipe Example | Json Pipe in Angular 9/8/7
- Angular Slice Pipe Example | Slice Pipe in Angular 9/8/7
- Angular Uppercase Pipe Example | Uppercase Pipe in Angular 9/8/7
- Angular LowerCase Pipe Example | LowerCase Pipe in Angular 9/8/7
- Angular Titlecase Pipe Example | Titlecase Pipe in Angular 9/8/7
- Angular KeyValue Pipe Example | KeyValue Pipe in Angular 9/8/7
- Call Method from One Component to Another Component in Angular
- Angular Push Object into Array Example