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

silverstone's avatar

Interpret this mysql query to eloquent

How can you interpret this mysql query into eloquent orm form or into a query builder: select count(client_id), client_id from bookings group by client_id order by count(client_id) desc;

I'm going to retrieve 'client_id' with most entries on the table. I can't seem to figure it myself, so i'm reaching out to you guys. Thanks!

0 likes
6 replies
jlrdw's avatar

Does this query work? Normally I see an as with a count like:

count(client_id) as total // or something
silverstone's avatar

it does work, tried that on my sql query. but how can i do it on eloquent or query builder form?

jlrdw's avatar

What do you have set up so far, like your models, have you setup any relations yet. And if you are new to eloquent relations Taylor has two tutorials now built into the docs. I'd highly suggest taking the tutorials, pay good attention to the second, where you use controllers.

silverstone's avatar

I have 3 models involved in this. -Client -Organization -Booking

I've set up Booking as a polymorphic relationship with the following fields on the table. -id -client_id ( this is intended so I can get the client who applied for an organization booking ) -bookable_id -bookable_type (App\Client, App\Organization) -etc **

Every models are set for polymorphic relationship and can be successfully saved, updated and deleted.

jlrdw's avatar
jlrdw
Best Answer
Level 75

OK, did you see in the querybuilder the raw expression example:

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Have you tried with using raw?

silverstone's avatar

I haven't, maybe that's the answer to my problem. I'll get back to you when it works.

Please or to participate in this conversation.