You should be able to do something like this:
...
->leftJoin('domain_user', 'domains.id', '=', 'domain_user.domain_id')
->select(DB::raw('COUNT(domain_user.user_id)'))
....
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have this eloquent query:
$domains = Domain::with('users')
->withCount('contracts')
->withCount('users')
->orderBy('id', 'DESC')
->paginate(10)
->through(fn($domain) => [
'id' => $domain->id,
'name' => $domain->name,
'numberOfContracts' => $domain->contracts_count,
'numberOfUsers' => $domain->users_count,
'userIds' => $domain->users->pluck('id')->toArray()
]);
Important in this query is those 2
'numberOfUsers' => $domain->users_count,
'userIds' => $domain->users->pluck('id')->toArray()
The relations are:
I want to replace the eloquent query from above with query builder:
$domains = DB::table('domains')
->leftJoin('contracts', 'domains.id','=','contracts.domain_id')
->select('domains.id', DB::raw('COUNT(contracts.domain_id) as numberOfContracts'), 'domains.name')
->groupBy('domains.id')
->where($filterService['filterCondition'])
->orderBy($filterService['sortBy'], $filterService['sortType'])
->paginate($filterService['items'])
->appends($filterService['queries']);
How can I get numberOfUsers (manyToMany) and userIds (the id associated for each domain) using the query builder ? Probably a callback function needed .... but not sure how....
Please or to participate in this conversation.