Adi Kurniawan Adi Kurniawan - 8 days ago 6
PHP Question

Populate dropdown in laravel with more than 2 attributes

So far I know how to populate dropdown using Eloquent (and pluck) is this

public function create()
{
$items = Item::all()->pluck('name', 'id');
return view('admin.item.create', compact('items'));
}


And with this

{!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}


I can generate this

<select name="items" class="form-control">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>


But now I want to create something like this

<select name="items" class="form-control">
<option value="1">Item 1 - Location</option>
<option value="2">Item 2 - Location</option>
<option value="3">Item 3 - Location</option>
</select>


I can only use pluck with 2 attributes. But now I want it to display 3 attributes. How do I do that? I'm using Laravel 5.3 by the way. Thanks for the help.

Answer

You have an array like [1=> "something",2=>"else"]. So you task is to either iterate the array and edit the values or select the the locations from the database and the use foreach or array_filter

So something like the following:

$items=[];
foreach(Item::all() as $item){
    $items[$item->id] = $item->name . " - " . $item->location->name; // build string to display here
}

Edit:

Your comment said location is at the same table so it would look like...

$items=[];
foreach(Item::all() as $item){
    $items[$item->id] = $item->name . " - " . $item->location; // build string to display here
}