Search

Laravel Collection Public API: keyBy

November 30, 2016 —John Koster

keyBy($keyBy)

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.

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

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

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<?php
2 
3$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 [
3 12 => array:3 [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 52 => array:3 [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 14 => array:3 [
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<?php
2 
3$results = $people->keyBy(function($item) {
4 return $item['id'];
5});

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<?php
2 
3$results = $people->keyBy(function($item) {
4 return md5($item['id']);
5});

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

1Collection {
2 #items: array:3 [
3 "c20ad4d76fe97759aa27a0c99bff6710" => array:3 [
4 "id" => 12
5 "name" => "Alice"
6 "age" => 26
7 ]
8 "9a1158154dfa42caddbd0694a4e9bdc8" => array:3 [
9 "id" => 52
10 "name" => "Bob"
11 "age" => 34
12 ]
13 "aab3238922bcc25a6f606eb525ffdc56" => array:3 [
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.