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')
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.
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.
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.
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.
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');
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With