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

How to check if an object or variable is an array, in JS?

How to find the average value of items in a Laravel Collection?

How to pick what array_intersect function to use in PHP?

What is Bubble sort, and how to write an implementation of it in PHP

How to hide certain file types from directory listings

What is an example of an object literal?

How to group a SQL statement in brackets/parenthesis

How to remove .php from the end of URLs with .htaccess

How to autoload helper files with composer?

What are generators in PHP, and how do they compare to arrays?