Home / Snippets / hasMany relation count number of relationship in laravel 8
hasMany relation count number of relationship in laravel 8 cover

hasMany relation count number of relationship in laravel 8

3.8K

3 years ago

0 comments

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this