Skip to content

Instantly share code, notes, and snippets.

@kevinruscoe
Created July 29, 2019 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinruscoe/61c414f7ce0102856d45d0b0130f9038 to your computer and use it in GitHub Desktop.
Save kevinruscoe/61c414f7ce0102856d45d0b0130f9038 to your computer and use it in GitHub Desktop.
Collection::macro(
'sortWithPreference',
function ($preference = [], $key = 'id') {
return $this->sort(
function ($a, $b) use ($preference, $key) {
$a = array_search(is_array($a) ? $a[$key] : $a->$key, $preference);
$b = array_search(is_array($b) ? $b[$key] : $b->$key, $preference);
if ($a === false && $b === false) {
return 0;
} elseif ($a === false) {
return 1;
} elseif ($b === false) {
return -1;
}
return $a - $b;
}
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment