0

With Laravel, I generate my list of object like that:

return Federation::lists('name','id');

So, this returns me [1 => 'elt1', 2 => 'elt2'] , etc

What I need is transform it to:

[{value => 1, text => 'elt1'},{value => 2, text => 'elt2'}]

is it a way to do it??

codedge
  • 4,754
  • 2
  • 22
  • 38
Juliatzin
  • 18,455
  • 40
  • 166
  • 325

2 Answers2

1

You can probably write your own collection class with a custom toCustomArray method inside.

class YourCollection extends \Illuminate\Database\Eloquent\Collection {
   public function toCustomArray() {
      // Your own implementation goes here. 
   }
}

Refresh your cache afterwards. Now you would be able to do:

Federation::pluck('name', 'id')->toCustomArray();

TL;DR

The lists method is deprecated since Laravel 5.2. Instead please use the pluck() method, optionally with a toArray() afterwards.

codedge
  • 4,754
  • 2
  • 22
  • 38
0

Maybe you can map through the collection and manipulate it

$array = $collection->map(function($item){
    return ["value" => $item->id, "text" => $item->name];
});

$json = json_encode($array);
Khalid Dabjan
  • 2,697
  • 2
  • 24
  • 35