Home » Laravel withCount(): Grab Similar Database Records Count Fastly

Laravel withCount(): Grab Similar Database Records Count Fastly

Loved it? Please Share on Social Media

Introduction

Hey, What’s up, everybody? I hope you are doing fine. Today, we will discuss an essential Laravel’s eloquent method: Laravel withCount. Laravel withCount is an excellent, eloquent method to count similar database records as needed.

In other words, it provides a functional solution for counting your database records. If you do it without the Laravel withcount function, you may succeed in your problem, but it will create lousy performance issues on your app.

But if you use Laravel withCount function, it will help you more to prevent the performance issues on your app. You can lazyload your counted data rows using this laravel withCount function.

Getting Ready Our Models for Laravel withCount Function:

So, in this tutorial, we’ll learn how to use the withCount function on our application and talk about some essential features of this function. We’ll use some example models for your workspace. We will use User, Tweet, and Comments Models for our reference.

Paste the following codes into your User.php file.

public function tweets()
{
    return $this->hasMany(Tweet::class);
}

public function comments()
{
    return $this->hasMany(Comment::class);
}

Getting Ready Our Controller for Laravel withCount Function:

Now, we will show the total number of tweets and comments the user has. You have to open your controller and paste the code below into your UserController file.

public function index()
{
    $users = User::withCount(['tweets', 'comments'])->get();
    return view('users', ['users' => $users]);
}

Getting Ready Our Blade File for Laravel withCount Function:

Next, We will create our users.blade.php file inside the views folder & paste the below code into our blade file.

<!doctype html>
<html>
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css">

    <title></title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">{{ __('Dashboard') }}</div>

                    <div class="card-body">
                        @if (session('status'))
                            <div class="alert alert-success" role="alert">
                                {{ session('status') }}
                            </div>
                        @endif

                        <table class="table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th class="text-center">Tweets</th>
                                    <th class="text-center">Comments</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($users as $user)
                                    <tr>
                                        <td>{{ $user->name }}</td>
                                        <td class="text-center">{{ $user->tweets_count }}</td>
                                        <td class="text-center">{{ $user->comments_count }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  </body>
</html>

Now, what are these tweets_counts and comments_count in our blade file? So, it comes from eloquent withCount function. That’s why we are seeing that.

Test The Application:

At last, we will start our local server using our artisan command. php artisan serve If there is no problem, our code will work fine, and the project will be running now at http://127.0.0.1:8000/ or http://locahost:8000/. You can know more from their documentation.

CONCLUSION:

Finished! That’s all about our tutorial. Although this tutorial cannot make you a pro coder, it will give you some fundamental knowledge of how to work with this function in the future. Thank you so much for reading the whole tutorial from the beginning. If this tutorial helps you a little bit, then remember to share this post on social media. If you have questions, suggestions, or tips regarding this post, let us know via our Contact Us page.


Loved it? Please Share on Social Media

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.