Laravel-5 how to populate select box from database

2019-01-13 03:08发布

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.

14条回答
Lonely孤独者°
2楼-- · 2019-01-13 04:04

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

查看更多
闹够了就滚
3楼-- · 2019-01-13 04:04

I have added toArray() after pluck

$items = Item::get()->pluck('name', 'id')->toArray();

{{ Form::select('item_id', [null=>'Please Select'] + $items) }}
查看更多
登录 后发表回答