Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AyobamilayeY's avatar

How to use Select with Count in Laravel

I am using Laravel-5.8 Eloquent to run a query. I want to get the total trucks utilized by a particular client for all their trips without counting a truck twice. I used the query below, but there is repetition of trucks used more than once:

$truckcount = Trip::where('client_id', $userClientId)
   ->select(\DB::raw("COUNT(truck_no) as count"))
   ->distinct()   
   ->get();

How do I write the correct Eloquent query to achieve this?

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ayobamilayey

Try this one-

$truckcount = Trip::where('client_id', $userClientId)
   ->select(\DB::raw("COUNT(DISTINCT truck_no) as count"))
   ->get();
5 likes

Please or to participate in this conversation.