Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active November 4, 2021 16:48
Show Gist options
  • Save kmuenkel/bebffacd94548ddd138d48d44b5a070d to your computer and use it in GitHub Desktop.
Save kmuenkel/bebffacd94548ddd138d48d44b5a070d to your computer and use it in GitHub Desktop.
Laravel Collection Macro for a dot-notation version of 'get' with wildcard support
<?php
Collection::macro('getDot', function ($index, $default = null) {
/** @var Collection $this */
$indexes = preg_split('~(?<!\\\)\.~', $index);
$indexes = array_map(function ($index) {
return preg_replace('~\\\.~', '.', $index);
}, $indexes);
$item = collect($this->all());
foreach ($indexes as $index) {
if (!($item instanceof Collection) || (strpos($index, '*') === false && !$item->has($index))) {
return $default;
}
if (strpos($index, '*') !== false) {
return $item->filter(function ($value, $key) use ($index) {
return fnmatch($index, $key);
});
}
$item = $item->get($index);
$item = (is_array($item) || $item instanceof stdClass) ? collect($item) : $item;
}
return $item;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment