Convert an Eloquent Collection to Array of Columns of Selected Models

Laravel ships with Array & JSON casting which is quite helpful in storing serialized data in the tables.

Suppose a scenario where you are trying to save an array of users and their nicknames in a field.

id | Name | Nickname
1 | John | Jo
2 | Paul | Po


'John' => 'Jo'
'Paul' => 'Po'

Cast the field in your Model:

protected $casts = [
    'nicknames' => 'array',

Get the selected records from the table

$selectUsers  =  User::select('id', 'name', 'nickname')->where('nickname', '!=', null)->get();
$records  =  $selectUsers->map->only(['name',  'nickname']);

Once you have the records you can proceed to create an array of key:value pairs from the records.

A function like mapWithKeys() can be really helpful that can recurse a Collection and form a key:value pairs.

You can do something like:

$keyed  =  $records->mapWithKeys(function  (array  $item,  int  $key)  {
	return  [$item['name']  =>  $item['nickname']];

$finalUsersNickArray  =  $keyed->all();

Now you can just insert it into the database:

    'nickname_array' => $finalUsersNickArray,