ホーム > Laravel > How to count the total number of related records in Laravel and display it in a list【withCount】
Laravel

How to count the total number of related records in Laravel and display it in a list【withCount】

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents for Laravel articles

Let's talk about how to count the total number of related records in Laravel and display them in a list. It can be easily done with withCount.

When might you use this?

For example,

① When you want to display the number of posts associated with a user in the user list. (⇦ We'll do this today.)

② When you want to display the number of likes or followers in a list.

This article is a summary of the official documentation

Test Environment

Laravel 6

Counting the total number of related records

This time, we will display the total number of posts that each user has posted in the user list.

If a user has multiple posts, it's enough to establish a one-to-many relationship.

For information on one-to-many relationships,

⇨How to create and display one-to-many relationships in Laravel【hasMany】

Write the relationship in the model.

User.php

    public function posts()
    {
        return $this->hasMany('App\Post');
    }

Write it in the controller.

Controller

    public function index()
    {
        $users = User::withCount('posts')->take(5)->get();
        dd($users);
    }

The output with dd will show the user list,

and each user's data will be as shown in this screenshot.

Output of withCount

In this way,

posts_count => 100

the total number of related records is included under the key name "relationship function name_count".

It's super convenient and makes me laugh.

⇨How to resolve the issue of not being able to retrieve withCount in Laravel

Summary

How was it?

We used withCount to count the total number of related records.

By the way, it seems that there is a book that supports Laravel 8.

If you plan to buy a Laravel book, this might be a good choice.

Popular Articles

Deploying a PHP7.4 + Laravel6 project to AWS EC2

Related Articles

How to create and display one-to-many relationships in Laravel【hasMany】

How to create and display many-to-one relationships in Laravel【belongsTo】

How to create one-to-one relationships in Laravel【hasOne】

How to create and display many-to-many relationships in Laravel【belongsToMany】

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!