Posts Learn Components Snippets Categories Tags Tools new 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

1369 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();

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)