Skip to content

Instantly share code, notes, and snippets.

@nuernbergerA
Last active February 29, 2024 19:24
Show Gist options
  • Save nuernbergerA/a06f70fb521bd4163163676d6731a60d to your computer and use it in GitHub Desktop.
Save nuernbergerA/a06f70fb521bd4163163676d6731a60d to your computer and use it in GitHub Desktop.
\Illuminate\Support\Collection::macro('sortByList', function (iterable $orderList, ?string $property = null) {
return $this
->sortBy(function($item) use ($property, $orderList) {
$value = $item;
if (is_iterable($item)) {
$value = $item[$property];
}
if (is_object($item)) {
$value = $item->$property;
}
$position = array_search($value, collect($orderList)->values()->toArray(), true);
return $position !== false ? $position : INF;
});
});
\Illuminate\Support\Collection::macro('sortKeyByList', function (iterable $orderList) {
return $this
->sortBy(function($item, $key) use ($orderList) {
$position = array_search($key, collect($orderList)->values()->toArray(), true);
return $position !== false ? $position : INF;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment