Last active
June 7, 2023 17:34
-
-
Save frankiejarrett/accba1238c288717c7e4afb9a062a743 to your computer and use it in GitHub Desktop.
Just some useful macros for Laravel Collections
This file contains hidden or 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 | |
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