Tip: Use the Laravel Arr helpers directly instead of using temporary collections
CodeWithCaen
Posted on April 9, 2024
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();
💖 💪 🙅 🚩
CodeWithCaen
Posted on April 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
laravel Tip: Use the Laravel Arr helpers directly instead of using temporary collections
April 9, 2024