Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active June 7, 2023 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjarrett/accba1238c288717c7e4afb9a062a743 to your computer and use it in GitHub Desktop.
Save fjarrett/accba1238c288717c7e4afb9a062a743 to your computer and use it in GitHub Desktop.
Just some useful macros for Laravel Collections
<?php
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
/**
* ```
* collect(['foo' => ['bar' => 'baz']])->recursive();
* collect(['foo' => ['bar', 'baz', 'qux']])->recursive(true);
* ```
* @return \Illuminate\Support\Collection
* @instantiated
*/
Collection::macro('recursive', function ($collectLists = false) {
return $this->map(function ($value) use ($collectLists) {
if ((is_array($value) && ($collectLists || ! array_is_list($value))) || is_object($value)) {
return collect($value)->recursive($collectLists);
}
return $value;
});
});
/**
* Remove items whose keys contain certain strings.
*/
Collection::macro('rejectKeysWith', function (array|string $needles) {
return $this->reject(function ($value, $key) use ($needles) {
return Str::of($key)->contains($needles);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment