Skip to content

Instantly share code, notes, and snippets.

@kevinruscoe
Created July 29, 2019 16:46
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