6

I have a line of code similar to the following:

Sport::pluck('id', 'name)

I am dealing with frontend JavaScript that expects a list in this format:

var list = [
 { text: 'Football', value: 1 },
 { text: 'Basketball', value: 2 },
 { text: 'Volleyball', value: 3 }
 ...
]

I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.

If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.

How would I approach this?

I initially tried something like this (without checking the documentation)

Sport::pluck(["id" => "value", "name" => "text]);

But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.

Any suggestions?

Barry D.
  • 549
  • 2
  • 6
  • 21

4 Answers4

10

Another method is to use map->only():

Sport::all()->map->only('id', 'name');
Eric
  • 251
  • 2
  • 8
4

The purpose of pluck is not what you intend to do,

Please have a look at below examples,

Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]

Syntax

$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

Please see the documentation.

Your output is possible using simple code.

Sport::selectRaw('id as value, name as text')->get();
Rahul
  • 18,271
  • 7
  • 41
  • 60
  • You're right. Your suggestion is a lot simpler and somehow a refreshing reminder that good ol' queries still do the trick. I guess I was too in the zone with Eloquent to think about giving the columns aliases in a regular query. Thanks for sharing. – Barry D. Apr 11 '19 at 21:46
2

You could use map.(https://laravel.com/docs/5.8/collections#method-map)

$mapped = Sport::all()->map(function($item, $index) {
 return [
   "id" => $item["id"],
   "name" => $item["text"]
 ];
});

This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend: https://laravel.com/docs/5.8/eloquent-resources

Marco
  • 1,579
  • 1
  • 19
  • 34
1

Try with toArray function:

Sport::pluck('id', 'name)->toArray();

Then you can return your result with json_encode php function;

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
Emmanuel HD
  • 191
  • 7