intelis intelis - 11 months ago 66
PHP Question

Laravel Eloquent data ranking

I am trying to range users, based on how many rows there are in the DB with ther id.

My dataset look like this (simplified):

A .... John
A .... John
B .... Mike
A .... John
B .... Mike
C .... Denis

I want first three unique names, ordered by how many times a value on the left appears.

Can I do that with Laravel's eloquent ORM?

A result would then be:



Answer Source

That's how you do it with Laravel's Eloquent ORM

->orderBy(DB::raw('count(name)'), 'desc')

If you are using Laravel 3 then use snake case:

Model::select('name')->group_by('name')->order_by(DB::raw('count(name)'), 'desc')->take(3)->get();

If you wish you may just use Query Builder (Fluent) by using DB::table('tableName')-> instead of Model::.


  • DB::raw() instructs Laravel not to put backtics there.
  • take() limits the rows.