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

October 26, 2018

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

<?php
$posts = Post::all();
        echo Form::select("post_id", $posts->pluck("title","id"));
        // $posts->pluck("title","id") will produce something like this:
        // [
        //   1 => "post title 1",
        //   5 => "Another post",
        // ...
        // ]

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:

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

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

<?php
$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']

For more details see here.