Imagine you have a "Post" model and you want to count the total number of "Comment" associated with it, you can write it like below.
# app/Http/Controllers/PostController.php public function show(int $postId) { $postsWithTotalCommentsCount = Post::withCount('comments')->findOrFail($postId); dd($postsWithTotalCommentsCount); }
Do note that using "withCount" is the safest way to count model relationships since it avoids the N+1 issue altogether.
Leave a reply