How to change key values for map collection in Laravel?

The map method in Laravel loops through a collection and passes each value in it to a specified callback function. We can also use this map() function to modify key values inside a map collection in Laravel. Using the 'mapWithKeys' method iterates through a map collection, allowing us to change the keys and values. Consider the code snippet below.

// Using mapWithKeys
$collection = collect([
    [
        'name' => 'Harry',
        'department' => 'IT',
        'email' => 'harry@scratchcoding.com',
    ],
    [
        'name' => 'Alice',
        'department' => 'Sales',
        'email' => 'alice@scratchcoding.com',
    ]
]);
 
$keyed = $collection->mapWithKeys(function ($item, $key) {
    return [$item['department'] => $item['name']];
});
 
$keyed->all();
 
/*
    [
        'IT' => 'Harry',
        'Sales' => 'Alice',
    ]
*/

In the code snippet above, the mapWithKeys function maps the department to the name of the employee. The output of the function is as shown above.

We can use the map function in different use cases. Consider the example shown below. Here, the map function maps the employees that belong to the IT department.

$users = $users->map(function ($item, $key) {
    if($item->department == 'IT') {
        return [
            'name' => ucwords($item->name),
            'email' => $item->email
        ];
    }
});

// $users variable output

Array
(
    [0] => Array
        (
            [name] => Harry
            [email] => harry@scratchcoding.com
        )
 )

The output stored in the $users array is as shown above.

We can use the map or mapWithKeys function for various use cases, and accordingly change the keys and values for them.