DEV Community

Cover image for Tip: Use the Laravel Arr helpers directly instead of using temporary collections
CodeWithCaen
CodeWithCaen

Posted on • Originally published at tips.desilva.se

Tip: Use the Laravel Arr helpers directly instead of using temporary collections

Here's another quick Laravel tip: 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().

use Illuminate\Support\Arr;

// Do this 👇
Arr::mapWithKeys($array, function (array $item, int $key) {
    return [$item['email'] => $item['name']];
});

// Instead of this 👇
collect($array)->mapWithKeys(function (array $item, int $key) {
    return [$item['email'] => $item['name']];
})->all();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)