I want to be able to sort the results of my collection by the status column in specific order.
The idea is to paginate the collection but giving priority in a specific order: [2, 1, ...], so the pending listings are shown first and the other after!
Does anyone has an idea on such method?
Thanks in advance.
If your status priority is not in numeric order (e.g. 2 > 1 > 3 > 0), you can alternatively pass a callback function to sortBy:
$collection = collect([
['name' => 'A', 'status' => 0],
['name' => 'B', 'status' => 3],
['name' => 'C', 'status' => 0],
['name' => 'D', 'status' => 1],
['name' => 'E', 'status' => 2],
['name' => 'F', 'status' => 1],
['name' => 'G', 'status' => 3],
['name' => 'H', 'status' => 1],
['name' => 'I', 'status' => 2],
['name' => 'J', 'status' => 3],
]);
// define status priority here
$statusPriorities = [2, 1, 3, 0];
$collection->sortBy(function($order) use($statusPriorities){
return array_search($order['status'], $statusPriorities);
})->values()->all();
Output:
[
[
"name" => "I",
"status" => 2,
],
[
"name" => "E",
"status" => 2,
],
[
"name" => "D",
"status" => 1,
],
[
"name" => "F",
"status" => 1,
],
[
"name" => "H",
"status" => 1,
],
[
"name" => "B",
"status" => 3,
],
[
"name" => "G",
"status" => 3,
],
[
"name" => "J",
"status" => 3,
],
[
"name" => "A",
"status" => 0,
],
[
"name" => "C",
"status" => 0,
],
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With