Skip to content

Use the Laravel Arr helpers directly instead of using temporary collections

Posted by author

Instead of creating a temporary collection just to use array helpers, you can use the Laravel Arr helpers directly.

This makes the code much more readable, as you don't need the cognitive load of having to consider the collect() logic and also having to convert it back to an array with all().

1// Do this 👇
2Arr::mapWithKeys($array, function (array $item, int $key) {
3 return [$item['email'] => $item['name']];
6// Instead of this 👇
7collect($array)->mapWithKeys(function (array $item, int $key) {
8 return [$item['email'] => $item['name']];

Syntax highlighting by

End of article