In this tutorial, I will explain laravel withcount multiple query examples. We have already seen how to use withCount in my previous tutorial.  Now in this tutorial, we will see how to use withCount multiple times in laravel eloquent query. In this example, we will count tolar number of posts and comments of all users in our apllication. 

That means how many posts they did and how many comments they did, we will count it. So before starting it, first see the example model code of the User model:

app/Models/User.php

<?php

namespace App\Models;

use Laravel\Scout\Searchable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable, Searchable;

    protected $fillable = [
        'name',
        'email',
        'password'
    ];

    public function posts() : HasMany
    {
        return $this->hasMany(Post::class);
    }

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

 

Now see the example code of laravel 9 withcount multiple:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

class TutorialController extends Controller
{   
    public function index()
    {   
        return User::withCount([
            'posts',
            'comments'
          ])->get();
    }
}

 

Now see the output of this query:

[
    {
        "id": 1,
        "name": "Aracely Crist",
        "email": "jtoy@example.net",
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "posts_count": 1,
        "comments_count": 2
    },
    {
        "id": 2,
        "name": "Akeem Hauck",
        "email": "pearlie.reinger@example.net",
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "posts_count": 1,
        "comments_count": 1
    }
]

 

Read also: How To Use WithCount In Laravel Eloquent Query?

 

Conclusion

In this laravel withcount multiple tutorial,  I have tried my best to let you know the clear concept of laravel multiple withcount example. Hope now after completing this tutorial, you will know laravel 9 multiple withcount and you will be able to solve your problem about withcount multiple laravel example.