Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor

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


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.
  <h1>{{ $post->title }}</h1>
  <p>Total Likes: {{ $post->likes_count }}</p>

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

Snippets by

PostSrc poster


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.


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

Other Code Snippets