Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert eloquent result to associative array in Laravel

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')
like image 927
Mehdi Avatar asked Apr 27 '17 18:04

Mehdi


People also ask

What is toArray () in Laravel?

toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.

What is protected $Hidden in Laravel?

According to http://laravel.com/docs/eloquent, one can Hide Attributes From Array Or JSON Conversion by using a protected $hidden variable in the Model. Great, however when running print_r(User::all()) the encrypted password is sent from server to client inside the User object.

What is hydrate in Laravel?

Laravel Core Adventures - Did you know? Ever wondered what "hydrate" means? I've been there. Then I realized it's just a fancy word for filling an object with data. In this Eloquent Builder example, Laravel fills a new collection object with models from an array.

How do you pluck in Laravel?

The Laravel pluck () as the name suggests, extracts certain values, as suggested. It literally plucks the information out from the given array and produces it as an output. However, it is most effective against objectives, but will work well against arrays too.


2 Answers

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');
like image 144
Laerte Avatar answered Oct 07 '22 00:10

Laerte


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();
like image 20
Mehdi Avatar answered Oct 07 '22 00:10

Mehdi