Using Arr::KeyBy() in Laravel 11.x & Laravel 12.x

In Laravel 11.x & Laravel 12.x, the Arr::keyBy() method is a powerful utility provided by the Illuminate\Support\Arr class. It allows you to transform an array by using a specific key or callback to index the array. This is particularly useful when you want to reindex an array based on a unique identifier or a computed value.

Example Usage

1. Using a Key Name

If your array items are associative arrays, you can use a key name to reindex the array.

use Illuminate\Support\Arr;

$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 3, 'name' => 'Doe'],
];

$keyedUsers = Arr::keyBy($users, 'id');
print_r($keyedUsers);

Output

[
1 => ['id' => 1, 'name' => 'John'],
2 => ['id' => 2, 'name' => 'Jane'],
3 => ['id' => 3, 'name' => 'Doe'],
]

2. Using a Callback Function

If you need more control over how the keys are generated, you can use a callback function.

use Illuminate\Support\Arr;

$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 3, 'name' => 'Doe'],
];

$keyedUsers = Arr::keyBy($users, function ($user) {
return 'user_' . $user['id'];
});
print_r($keyedUsers);

Output

[
'user_1' => ['id' => 1, 'name' => 'John'],
'user_2' => ['id' => 2, 'name' => 'Jane'],
'user_3' => ['id' => 3, 'name' => 'Doe'],
]

3. Using with Objects

Arr::keyBy() also works with arrays of objects.

use Illuminate\Support\Arr;

class User
{
public function __construct(public $id, public $name) {}
}
$users = [
new User(1, 'John'),
new User(2, 'Jane'),
new User(3, 'Doe'),
];

$keyedUsers = Arr::keyBy($users, 'id');
print_r($keyedUsers);

Output

[
1 => User { id: 1, name: 'John' },
2 => User { id: 2, name: 'Jane' },
3 => User { id: 3, name: 'Doe' },
]