9

How can convert the result from eloquent to associative array. I need to select tow column and have one as key and another as value. Here is the closet I got, however the value is an array. I want it to be only "my_value" column.

$array = Post::select('my_key','my_value')->get()->keyBy('my_key')
3
  • What results do you get with this code? And what do you expect to get? Give some examples. Commented Apr 27, 2017 at 19:06
  • I was looking for array:2 [▼ "key1" => "value1" "key2" => "value2" ] Commented Apr 28, 2017 at 2:57
  • The above approach after converting toArray was giving me: array:2 [▼ "key1" => array:2 [▼ "my_key" => "key1" "my_value" => "value1" ] "key2" => array:2 [▼ "my_key" => "key2" "my_value" => "value2" ] ] Commented Apr 28, 2017 at 3:03

2 Answers 2

25

You should use lists (Laravel 5.1) or pluck (Laravel 5.2+):

$array = Post::lists('my_value', 'my_key');

or

$array = Post::pluck('my_value', 'my_key');
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, looks like lists have been renamed to plunk, I just modified it a bit $array = Post::plunk('my_value', 'my_key')->toArray();
Just wanted to point out for any future people: @Mehdi's answer is a typo. It is "pluck" not "plunk".
@Mehdi pluck not plunk
6

I found a way to do so, I'm not sure whether it's proper way to do this performance wise though...

$array = Post::select('my_key','my_value')->get()->mapWithKeys(function ($item) {
            return [$item['my_key'] => $item['my_value']];
        })->toArray();

1 Comment

You can just $array = $array ->toArray() to convert object as string. Its buildin method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.