How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

Laravel: How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

The answer used to be list(), but now the answer is pluck()

  1. $posts = Post::all();
  2.  
  3.         echo Form::select("post_id", $posts->pluck("title","id"));
  4.  
  5.         // $posts->pluck("title","id") will produce something like this:
  6.         // [
  7.         //   1 => "post title 1",
  8.         //   5 => "Another post",
  9.         // ...
  10.         // ]

The first param is the actual value you want to 'pluck', and the second value is how you want it keyed. For most cases the second param will be 'id'.

You can also use pluck with just 1 param like this:

  1. $collection = collect([
  2.     ['product_id' => 'prod-100', 'name' => 'Desk'],
  3.     ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5.  
  6. $plucked = $collection->pluck('name');
  7.  
  8. $plucked->all();
  9.  
  10. // ['Desk', 'Chair']

But if more than one item with the same key exists, the last matching one will be used. For example:

  1. $collection = collect([
  2.     ['brand' => 'Tesla',  'color' => 'red'],
  3.     ['brand' => 'Pagani', 'color' => 'white'],
  4.     ['brand' => 'Tesla',  'color' => 'black'],
  5.     ['brand' => 'Pagani', 'color' => 'orange'],
  6. ]);
  7.  
  8. $plucked = $collection->pluck('color', 'brand');
  9.  
  10. $plucked->all();
  11.  
  12. // ['Tesla' => 'black', 'Pagani' => 'orange']

For more details see here.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What is the max size, by default, of GET variables?

How to change the order that migrations happen?

What does 'final class' and 'final function' (final method) mean in PHP?

Is multiple inheritance supported in PHP?

How does PHP compare objects?

How to hide certain file types from directory listings

How to replace whitespace with a single space

How to set up an alias to map one directory to another destination

How to round a number in JS?

How to find the 2nd most common item in an array?