How to count relationship data with main model in laravel by using withCount() eloquent method with hindi video.
Also ask: withCount() method in laravel, how to count laravel relationship data.
Laravel eloquent withCount() method
When you want to count a model related records in laravel then use withCount() method. We pass one or more relationship names in this method which data count.
Let understand by example there are three models Post, View and Comment now we get all posts data with count number of views and comments.
Post ModelIn Post model define two relations views and comments.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } public function views() { return $this->hasMany(View::class); } }PostController
Now we get all posts data with their related views and comments count. withCount() method add extra column in array which name define as add a '_count' after relationship name like 'views_count
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller{ public function index(){ $Posts = Post::withCount(['comments', 'views'])->get(); foreach($posts as $post){ echo "Post Name".$post->name; echo "Total Views".$post->views_count; echo "Total Comments".$post->comments_count; } dd($Posts); } }
Here we explain laravel eloquent concepts with advanced web tutorial. Also provide laravel tutorial with hindi videos.
Anmol Sharma
I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.
Related tutorial links
- part 1 laravel hasOne() relationship
- part 2 laravel one to many relationship
- part 3 Has One Of Many relationship
- part 4 laravel hasOneThrough relationship
- part 5 laravel hasManyThrow() relationship
- part 6 laravel many to many relationship
- part 7 one to one polymorphic relationship
- part 8 laravel one to many polymorphic relationship
- part 9 many-to-many polymorphic relationship
- part 10 laravel eloquent has vs whereHas method
- part 11 laravel whereDoesntHave and whereDoesntHave
- part 12 laravel withCount() method
- part 13 eager vs lazy loading