Laravel Multiple Joins with Counts (Not Eloquent)

I’m going to convert this Eloquent query to DB query in Laravel.

$users = User::withCount("addresses", "cars")->get();

The above one is Eloquent and it’s working well.
But I’d like to do this with DB query.

I tried to do as following but I couldn’t get expected result.

$users = DB::table("users")->join("addresses", "", "=", "addresses.user_id")
->join("cars", "", "=", "cars.user_id") 
->selectRaw(",, count( as addresses_count, count( as cars_count")
->groupBy("", "")

The result value of addresses_count and cars_count were same and it was multiplied value of two.

Any help would be appreciated.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

you just need to add distinct in count like:

$users = DB::table("users")->join("addresses", "", "=", "addresses.user_id")
->join("cars", "", "=", "cars.user_id") 
->selectRaw(",, count(distinct as addresses_count, count(distinct as cars_count")
->groupBy("", "")

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x