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
$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)
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