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 use array for
Form::select
. So I passed array like below:In your view:
In your controller, add,
And in your view, use
In select box, it will be like this,
Laravel >= 5.3 method lists() is deprecated use
pluck()
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:
in select box it will be like this
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();
For Laravel 5 :
Push an item onto the beginning of the collection.
Many has been said already but keep in mind that there are a times where u don't want to output all the records from the database into your select input field ..... Key example I have been working on this school management site where I have to output all the noticeboard categories in a select statement. From my controller this is the code I wrote
Noticeboard:: groupBy()->pluck('category')->get();
This way u get distinct record as they have been grouped so no repetition of records
Controller
compact('campaignStatus') will result in [id=>status]; //example [1 => 'pending']
View