Posts Learn Components Snippets Categories Tags Tools 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

283 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.

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

new

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

Sponsors 👑

+ Add Yours
)