Flatten Eloquent collection to array with key and value

If you have a result from Eloquent which is a collection where every value is on it’s own row, you can use mayWithKey() create an array in a specific format.


// A collection from Eloquent where each setting are on separate rows in a

$settings = Settings::all();

/*
| id | key   | value      |
|----|-------|------------|
| 1  | color | white      |
| 2  | size  | 2em        |
| 3  | font  | Comic Sans |
*/

// Merge key and value for each row to a array;
$settingsList = $settings->mapWithKeys(function ($item) {
    return [$item['key'] => $item['value']];
});

/*
$settingsList = [
    'color' => 'white',
    'size' => '2em',
    'font' => 'Comic Sans'
]
*/