Skip to content

Instantly share code, notes, and snippets.

@chasecmiller
Last active March 5, 2021 19:08
Show Gist options
  • Save chasecmiller/027896f5518d44141687cca4da4c10b7 to your computer and use it in GitHub Desktop.
Save chasecmiller/027896f5518d44141687cca4da4c10b7 to your computer and use it in GitHub Desktop.
Getting the row number for the current db entry in Laravel.
This is a very inefficient way to do it once the db is huge. But it works. For the example, the user id is 5.
$userId = 5;
\DB::statement('SET @row=0');
$user = \App\Models\User::whereRaw('1=1')
->select([
\DB::raw('@row:=@row+1 as row'),
\DB::raw('count(*) as c'),
'users.*'
])
->groupBy('id')
->orderBy('c','desc')
->get()
->filter(function($entity) use ($userId) {
return $entity->getKey() == $userId;
})
->first();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment