Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - Sort Collection by Column by Array's Order

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.

like image 294
Tomas C. Lopes Avatar asked Sep 16 '25 05:09

Tomas C. Lopes


1 Answers

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,
     ],
   ]
like image 50
CBrach Avatar answered Sep 17 '25 20:09

CBrach