Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

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

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

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

Other Code Snippets

More