I want to create a select box like the one below using illuminate\html :
<select>
<option value="$item->id">$item->name</option>
<option value="$item->id">$item->name</option>
</select>
In my controller I tried this:
public function create()
{
$items = Items::all(['id', 'name']);
return view('prices.create', compact('id', 'items'));
}
And in my view this:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
{!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>
The issue is that instead of $item->name
is displaying all the info of the entity.
Laravel provides a Query Builder with lists() function
In your case, you can replace your code
$items = Items::all(['id', 'name']);
with
$items = Items::lists('name', 'id');
Also, you can chain it with other Query Builder as well.
$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');
source: http://laravel.com/docs/5.0/queries#selects
Update for Laravel 5.2
Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be
$items = Items::pluck('name', 'id');
or
$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');
ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists