Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nikocraft's avatar

how to get key => value

I have this code:

Setting::where('section', $section)->select('key', 'value')->pluck('value')->toArray();

it produces this:

0 => "true" 1 => "native" 2 => "true" 3 => "true"

I need this

 enable => "true"
 type => "native"
 must_be_registered => "true"
 allow_nested => "true"

how do I get that? I tried pluck('key', 'value') but that did not return all values from DB for some reason some were missing, this is what came out:

 array:3 [▼
      "true" => "allow_nested"
      "native" => "type"
 ]

it came out in value => key order and was missing keys and values

How can I get key => value?

0 likes
3 replies
zachleigh's avatar

What does this produce?

Setting::where('section', $section)->select('key', 'value')->pluck('value');
nikocraft's avatar

Hi @zachleigh

solution for me was this:

$settings = Setting::where('section', $section)->select('key', 'value')->pluck('value', 'key')->toArray();

it gave correct array back and then I did

return (object) $settings;

notice the order of pluck('value', 'key')

any other way and it would screw up results

2 likes
Cronix's avatar

So you basically just want an associative array?

$settings = Setting::where('section', $section)->select('key', 'value')->get();
$associativeArray = $settings->mapWithKeys(function ($item) {
        return [$item['key'] => $item['value']];
});
2 likes

Please or to participate in this conversation.