Add $collection->toDot();
method to transform the collection to the dotted notation.
#48036
-
At my company we are in need for this function, the My approach: Collection::macro('toDot', function (): Collection {
/* @var $this Collection taking the identical fqcn for later reconstruction, otherwise it might mess with custom collections */
$collection = get_class($this);
// Prefixing the keys of the array with an underscore, otherwise the keys will be lost and mapped to an chronological default order
// possibly breaking the collection content for certain scenarios.
$prepend = '_';
return $collection
::make(Arr::dot($this, $prepend))
->mapWithKeys(function ($value, string $dottedKey) use ($prepend): array {
return [
substr($dottedKey, strlen($prepend)) => $value,
];
});
}); |
Beta Was this translation helpful? Give feedback.
Answered by
henzeb
Aug 11, 2023
Replies: 1 comment 1 reply
-
I'd call it dot and not toDot. Unfortunately, that method already exists: https://laravel.com/docs/10.x/collections#method-dot |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
mikevandiepen
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd call it dot and not toDot. Unfortunately, that method already exists: https://laravel.com/docs/10.x/collections#method-dot