Posts Learn Snippets Categories Tags About
/

How to Get Number of Relations Count in Laravel 8

Learn how to where count relationship in Laravel 8 to get the total relation in a straight forward and an efficient manner

Created on Jun 26, 2021

8 views

To get the total count of the relationship of a model you can make use of the "withCount" method available to every Laravel model.

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.

Created by

PostSrc poster

PostSrc

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.