I have the following collection:
$configuration = DB::table('configuration')->get();
Illuminate\Support\Collection {#562 ▼
#items: array:7 [▼
0 => {#1447 ▼
"configuration_name": "assign_device_email_addresses"
"configuration_value": "[email protected]|[email protected]"
}
1 => {#1357 ▼
"configuration_name": "helpdesk_platform_url"
"configuration_value": "https://clouddesk.com/app/itdesk/ui/requests/{helpdeskurl}/details"
}
2 => {#1446 ▼
"configuration_name": "mail_encryption"
"configuration_value": "tls"
}
3 => {#563 ▼
"configuration_name": "mail_host"
"configuration_value": "exampleserver.example.com"
}
4 => {#1292 ▼
"configuration_name": "mail_password"
"configuration_value": "encrypted_password"
}
5 => {#1291 ▼
"configuration_name": "mail_port"
"configuration_value": "465"
}
6 => {#885 ▼
"configuration_name": "mail_username"
"configuration_value": "mobiles"
}
]
}
With this structure I can only access each item via the following statements:
$configuration[0]->configuration_name
$configuration[0]->configuration_value
$configuration[1]->configuration_name
$configuration[1]->configuration_value
etc.
I want to be able to access it via:
$configuration->assign_device_email returning "[email protected]|[email protected]".
$configuration->mail_host returning "exampleserver.example.com".
etc.
How can I can convert this collection so that I can access each property value via it's configuration_name?
I have tried the below which got me closer, but I still can't access it via statements like: $configuration->mail_port etc.
$configuration2 = DB::table('configuration')->get()
->mapWithKeys(function($configuration2){
return [$configuration2->configuration_name => $configuration2->configuration_value];
});
I think this fails as the above statement still returns an array:
Illuminate\Support\Collection {#1500 ▼
#items: array:7 [▼
"assign_device_email_addresses" => "[email protected]|[email protected]"
"helpdesk_platform_url" => "https://clouddesk.com/app/itdesk/ui/requests/{helpdeskurl}/details"
"mail_encryption" => "tls"
"mail_host" => "exampleserver.example.com"
"mail_password" => "encrypted_password"
"mail_port" => "465"
"mail_username" => "mobiles"
]
}
Anyone have any ideas? I feel like I am getting closer with it, but collections confuse me a bit.
I think I am essentially after something like this:
Illuminate\Support\Collection {#1507 ▼
"assign_device_email_addresses" : "[email protected]"
"helpdesk_platform_url" : "https://cloudesk.com/app/itdesk/ui/requests/{helpdeskurl}/details"
"mail_encryption" : "tls"
"mail_host" : "[email protected]"
"mail_password" : "encrypted_password"
"mail_port" : "465"
"mail_username" : "mobiles"
}
CodePudding user response:
You can Arr
helper to map in key value:
$configuration = DB::table('configuration')->get();
$configuration = Arr::pluck($configuration, 'configuration_value','configuration_name');
also, add below line to import class:
use Illuminate\Support\Arr;