sometimes it's necessary to sort all elements of a collection by another array. moreover the ids may not belong to the collection's ids, this can be done using the following method
if the collection's id values are not present in the array of ids to sort by, then these ids will end up at the end of the sorted collection
/**
* @param \Illuminate\Support\Collection $collection
* @param array $sortByIds
* @return \Illuminate\Support\Collection
*/
function sortCollectionByArraysIds($collection, $sortByIds)
{
$idsOnThisNode = array_intersect($sortByIds, $collection->pluck('id')->toArray());
$idsSort = array_merge(
$ids ,
array_diff($collection->pluck('id')->toArray(), $ids)
);
$collection = $collection->sort(function ($modelCategory, $modelCategorySecond) use ($ids ) {
return (
array_search($modelCategorySecond->id, $ids ) >
array_search($modelCategory->id, $ids ))
? -1 : 1;
});
return $collection;
}
Comments