Laravel WithCount() Eager Loading Query Example

Hello Artisan

In this example tutorial, I will show you how can you get a single user model which has a max number of posts (User has many posts). This is an example query, you can check it for every model which has a relationship like that.

I will use laravel withcount orderby query structure to do that. In this example, suppose we will count every user with how many posts already they have been published. We will use withCount rather with to eager loading.

So let's see our example query.

app\User.php

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

 

Then run this following query in any controller to get number of user data with post_count.

\App\User::withCount('posts')
         ->orderBy('posts_count','desc')
         ->get();

 

Read also : Laravel Eager Loading Return Specific Columns Example

 

Now just let's have a try to check it. So laravel count hasmany relations is done. hope it can help you.

 

#laravel #laravel-7 #eloquent-tips