Home / Snippets / How to Get Number of Relations Count in Laravel 8
How to Get Number of Relations Count in Laravel 8 cover

How to Get Number of Relations Count in Laravel 8

323

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this