Laravel-5 how to populate select box from database with id value and name value
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
Laravel >= 5.3 method lists() is deprecated use pluck()
$items = Items::pluck('name', 'id');
{!! Form::select('items', $items, null, ['class' => 'some_css_class']) !!}
This will give you a select box with same select options as id numbers in DB
for example if you have this in your DB table:
id name
1 item1
2 item2
3 item3
4 item4
in select box it will be like this
<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
I found out that pluck now returns a collection, and you need to add ->toArray() at the end of pluck...so like this: pluck('name', 'id')->toArray();
Just change your controller to the following:
public function create()
{
$items = Subject::all(['id', 'name']);
return View::make('your view', compact('items));
}
And your view to:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
<select class="form-control" name="item_id">
@foreach($items as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
@endforeach
</select>
</div>
Hope this will solve your problem