Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel PHP move collection item to the top of the collections

This is just in case someone else has the same question and like me did not find a suitable answer to solve it.

I had a collection that had to be filtered so the active item comes first on the collections when a certain value was passed.

Illuminate\Database\Eloquent\Collection {
    0 => array:2 [
      "id" => 1
      "name" => "Bogan, Weissnat and Jenkins"
    ]
    1 => array:2 [
      "id" => 4
      "name" => "Grady-Barrows"
    ]
    2 => array:2 [
      "id" => 7
      "name" => "Howe and Sons"
    ]
    3 => array:2 [
      "id" => 3
      "name" => "Macejkovic-Altenwerth"
    ]
  ]
}

Needed to move an item top based on the id which is passed by URL

like image 979
mukolweke Avatar asked Oct 15 '25 14:10

mukolweke


1 Answers

$activeId = 3; // Your active item id
$collection = $collection
      ->sortBy('id')
      ->sortBy(fn($item) => $item->id !== $activeId);

This will sort your collection by id and move a specific item to the top.

(PHP7.4+ for arrow function)

like image 154
Sirapat Avatar answered Oct 17 '25 05:10

Sirapat