Skip to content
Advertisement

Sort Laravel Collection by custom order, other than asc or desc

I have this array as Laravel Collection :

JavaScript

And I need to sort it by status, not by asc or desc, but the records with status 2 should be first on the list, then status 1 then status 3.

I can’t figure out how to achive this, thank you in advance.

Advertisement

Answer

Hi had similar issue,

JavaScript

['2', '1', '3'] (Status with number 2 will be first because his position key is 0, just change the order as you need.

Or you can create an array like ['2' => 1, '1' => 2, '3' => 3]

use like return $arry_of_order[$item->status]; (faster then calling array_search each time)


P.S. If you can use Database (in case MySQL), as other people here suggested, you should stick to it, $query->orderByRaw("FIELD(status, '2', '1', '3')")

For PostgreSQL look here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement