Search

Laravel 5 Collections: Transforming Collection Element Keys With keyBy

April 22, 2018 —John Koster

The keyBy method is used to create a new Collection instance where the keys of the new key/value pairs are determined by a $keyBy callback function (a string value can also be supplied instead of a function). The signature of the callback function is keyBy($item), where the $item is the actual item in the collection. This method does not change the original Collection instance will will return a new, modified, Collection instance.

#Signature

1public function keyBy(
2 $keyBy
3);

#Example Use

The following sample will be used to demonstrate the keyBy method:

1// Create a new collection.
2$people = collect([
3 ['id' => 12, 'name' => 'Alice', 'age' => 26],
4 ['id' => 52, 'name' => 'Bob', 'age' => 34],
5 ['id' => 14, 'name' => 'Chris', 'age' => 26]
6]);

In the following example, we will create a new collection instance where the key of each item is the persons id. We will not supply a callback function in this example, but rather pass the name of the value we want to use as the key as as string:

1$results = $people->keyBy('id');

After the above code has executed, the $results variable will contain a value similar to the following output:

1Collection {
2 #items: array [
3 12 => array [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 52 => array [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 14 => array [
14 "id" => 14
15 "name" => "Chris"
16 "age" => 26
17 ]
18 ]
19}

We can also achieve the exact same results by using a callback function like so:

1$results = $people->keyBy(function($item) {
2 return $item['id'];
3});

However, the above example is overly complicated if all we were interested in was just the id of the person. We could do something a little more interesting, such as returning a simple hash of each persons id to use as the new key:

1$results = $people->keyBy(function($item) {
2 return md5($item['id']);
3});

After the above code has executed, the new $results variable would contain a value similar to the following output:

1Collection {
2 #items: array [
3 "c20ad4d76fe97759aa27a0c99bff6710" => array [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 "9a1158154dfa42caddbd0694a4e9bdc8" => array [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 "aab3238922bcc25a6f606eb525ffdc56" => array [
14 "id" => 14
15 "name" => "Chris"
16 "age" => 26
17 ]
18 ]
19}

The same method could just as easily be applied to other hashing libraries, such as the hashids.php library.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.