How to do Laravel Eloquent get with a specific item appearing first for pagination

422 Views Asked by At

I have a use case where I need to get all the rows from a table with the currently selected row appearing first and show the rest as the user scrolls through the table. I currently have it setup where I use the eloquent find to fetch the individual item and then use the eloquent get and merge the results if the page number is 1. Is there a better way to handle this or is this the best way to handle this use case?

2

There are 2 best solutions below

3
Kalmár Gábor On BEST ANSWER

You can use SQL's order by, as mentioned here:

$selectedImageId = 2;
$images = \App\Models\Image::orderByRaw('case when id=? then -1 else 0 end, created_at desc', [$selectedImageId])->get();
0
AudioBubble On

I think this should work:

$result = Model::orderByRaw("id = $selected DESC")->get();