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

2

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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay