Laravel - pluck with specified keys

Barry D. picture Barry D. · Apr 10, 2019 · Viewed 15.5k times · Source

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?

Answer

Eric picture Eric · Jun 26, 2019

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

Sport::all()->map->only('id', 'name');