I have this array as Laravel Collection :
"data": [
{
"id": 863368,
"reference": "Ref 1",
"status": 1
},
{
"id": 863391,
"reference": "Ref 2",
"status": 2
},
{
"id": 863390,
"reference": "Ref 3",
"status": 2
},
{
"id": 863396,
"reference": "Ref 4",
"status": 3
}
];
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.
Hi had similar issue,
$final = $collection->sortBy(function($item){
return array_search($item->status, ['2', '1', '3']);
});
['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 DB (MySql), as other people here suggested, you should stick to it, $query->orderByRaw("FIELD(status, '2', '1', '3')")
For PostgreSQL look here
If you are getting data from MySQL, you can just change ORDER BY like this:
ORDER BY FIELD(status, 2, 1, 3)
You can get this by using orderByRaw
Model::orderByRaw('FIELD(status, 2, 1, 3)')->get();
Also By using orderBy
Model::orderBy(DB::raw('FIELD(status, 2, 1, 3))'))->get();