'Sort collection similar to query with cases in Laravel?
How can I apply this ordering to a collection instead?
orderByRaw('(start_datetime < NOW()),
(case when start_datetime > NOW() then start_datetime end) ASC,
(case when start_datetime < NOW() then start_datetime end) DESC')
sortBy(function ($p) {
return $p->events->pluck('start_datetime'); // Collection of Carbon datetimes, but what do I do from here?
});
Is it even possible?
Thanks!
Solution 1:[1]
https://laravel.com/docs/8.x/collections#method-sortby
You can, but it's not pretty. Basically you can pass an array of conditions to sortBy, like
// ORDER BY column1 ASC, column2 DESC
sortBy([['column1', 'asc'], ['column2', 'desc']])
For more complicated sorting, you can pass an array of closures instead. Using the spaceship operator (<=>) for comparison helps a lot.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IGP |
