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

0re1's avatar
Level 1

How to add a row number to result set?

Hi I would like to have added line number to result set with the number specifying the order in result set. Eg: I have competitors men and women and I would like to know what was the order of Jane Doe in the competition among women.

rs = Competitor::where('sex','w')->orderBy('finish_time')->get();

and now somehow get her order...

..->getLineNumber('Jane Doe');

Thank you for your help! :)

0 likes
9 replies
jlrdw's avatar

You can order by more than one field. And setup a counter var.

1 like
jlrdw's avatar

Before foreach

$k =0;

Inside the for each

$k = $k + 1;

Now make k one of your columns.

0re1's avatar
Level 1

So I cannot get the order of Jane Doe without getting the whole result set and I have to construct foreach and go one record by one in PHP? SQL has something like this:

SELECT competitor.finish_time, competitor.name, number = ROW_NUMBER() OVER (ORDER BY competitor.finish_time)
tykus's avatar
tykus
Best Answer
Level 104

But the OP does not want to iterate over the collection - instead wants to find a named competition and get their position in the collection:

$name = 'Jane Doe';
$competitiors = Competitor::where('sex','w')->orderBy('finish_time')->get();
$position = $competitiors->search(function ($person, $key) use ($name) {
    return $person->name == $name;
});

return $position + 1; //since it will be a zero-indexed collection
1 like
0re1's avatar
Level 1

@tykus_ikus It is nice but it is still iteration over result set - I would like to have something to ask DB directly - if it is possible - simply how to ask: What was the order of Jane Doe among women?

tykus's avatar

If you are just hitting a single competitor in the query then your solution will be database-specific - as you say SQL has a ROW_NUMBER() function, but this is not available in MySQL (is this your DB of choice here?)

0re1's avatar
Level 1

yes MySQL... so Eloquent cannot address this since it is not common in various SQLs to ask on the result order in result set...

tykus's avatar

A DB::select type query is necessary in this case - there are a number of articles like this which show you how to emulate the ROW_NUMBER() functionality in MySQL

1 like

Please or to participate in this conversation.