Posts Learn Snippets Categories Tags About
/

hasMany relation count number of relationship in laravel 8

Learn how to use withCount to count the number of relation of an eloquent model

Created on Jun 30, 2021

8 views

If you want to count the total number of a relationship that an eloquent model has in Laravel, you can make use of the "withCount" method.

So imagine you have a relation of "post" has many "likes" and you want to count the total number of likes of the post, instead of writing a separate query you can use "withCount" method.
$post = Post::withCount('likes')->first();

return view('posts.index', ['post' => $post]);

And once you have return it to your views, you can access the total count using the "likes_count" property.
<div>
  <h1>{{ $post->title }}</h1>
  <p>Total Likes: {{ $post->likes_count }}</p>
</div>

Count multiple relationships
If you want to count multiple relationships you can provide an array to the "withCount" method.
$post = Post::withCount(['comments', 'likes'])->first();

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.