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();
Leave a reply