Created
May 24, 2023 03:36
-
-
Save kmuenkel/3820451c4f697065670c6a4a3bfbff2c to your computer and use it in GitHub Desktop.
Laravel Collection Macro to Sort Results and All Nested Entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function sortRecursive() | |
{ | |
$sortRecursive = function (callable $sortBy = null, $options = SORT_REGULAR, bool $descending = false): Collection { | |
/** @var Collection|Request $this */ | |
$sort = $sortBy ? fn (array $item): Collection => collect($item)->sortBy($sortBy, $options, $descending) : | |
fn (array $item): Collection => $descending ? collect($item)->sortDesc() : collect($item)->sort(); | |
return collect(($self = function ($item) use (&$self, $sort) { | |
return is_array($item) ? $sort($item)->map($self)->all() : $item; | |
})($this->all())); | |
}; | |
$sortKeysRecursive = function (callable $sortBy = null, $options = SORT_REGULAR, bool $descending = false): Collection { | |
/** @var Collection|Request $this */ | |
$sort = $sortBy ? fn (array $item): Collection => collect($item)->sortKeysUsing($sortBy) : | |
fn (array $item): Collection => collect($item)->sortKeys($options, $descending); | |
return collect(($self = function ($item) use (&$self, $sort) { | |
return is_array($item) ? $sort($item)->map($self)->all() : $item; | |
})($this->all())); | |
}; | |
Collection::macro('sortRecursive', $sortRecursive); | |
Collection::macro('sortKeysRecursive', $sortKeysRecursive); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment