Total Count with eloquent

I have a two table users and orders . i want to get users with Total Orders Count. How can I do this with eloquent?

Here is my query

User::with('orders')->where('status','active')->get();

>Solution :

You can use withCount for this.

https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models

User::withCount('orders')->where('status','active')->get();

Leave a Reply