Using keyBy Collection Method in Laravel

The collection method keyBy keys a collection by a given key. Copied straight from the docs:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

I found this very useful if you have to search for a given value in a nested associative array.

// this function returns a collection of users with its corresponding greeting
function user_greeting()
    {
        // Collection of user info
        $users = collect([
            [
                'id' => 1,
                'name' => 'Shawn',
            ],
            [
                'id' => 2,
                'name' => 'Sam',
            ]
        ]);

        // Collection of greetings
        $greetings = collect([
            [
                'greeting' => 'hello',
                'user_id' => 1,
            ],
            [
                'greeting' => 'hi',
                'user_id' => 2,
            ]
        ]);

        $keyed_greeting = $greetings->keyBy('user_id');

        // because $greetings is now keyed, we can have an efficient lookup
        // only 1 loop, O(n)
        $users_greetings = $users->map(function ($user) use ($keyed_greeting) {
            $user['greeting'] = $keyed_greeting->get($user['id'])['greeting'];
            return $user;
        });

        return $users_greetings;
    }
		
		
// it's better than doing this:
	$user_greetings = [];

	// Nested loop, O(n^2)
	foreach ($users as $user) {
			// Loop through the greetings collection to find the corresponding greeting
			foreach ($greetings as $greeting) {
					if ($greeting['user_id'] === $user['id']) {
							// If the user_id matches, assign the greeting to the user
							$user['greeting'] = $greeting['greeting'];
							break;  // Exit the inner loop as we've found the corresponding greeting
					}
			}

			$user_greetings[] = $user;
	}
	return $user_greetings