Laravel-5如何使用ID值和名称值填充数据库中的选择框 [英] Laravel-5 how to populate select box from database with id value and name value

查看:109
本文介绍了Laravel-5如何使用ID值和名称值填充数据库中的选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 illuminate \ html 创建一个如下所示的选择框:

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'));
}

在我看来,这是

<div class="form-group">
    {!! Form::Label('item', 'Item:') !!}
    {!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>

问题在于,不是显示$item->name而是显示实体的所有信息.

The issue is that instead of $item->name is displaying all the info of the entity.

推荐答案

Laravel为查询生成器提供了list()函数

Laravel provides a Query Builder with lists() function

根据您的情况,您可以替换代码

In your case, you can replace your code

$items = Items::all(['id', 'name']);

使用

$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');

来源: http://laravel.com/docs/5.0/queries#selects

Laravel 5.2的更新

非常感谢@jarry.如您所述,Laravel 5.2的功能应为

Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be

$items = Items::pluck('name', 'id');

$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');

ref: https://laravel.com/docs/5.2/upgrade# upgrade-5.2.0 -查看弃用列表"

ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists

这篇关于Laravel-5如何使用ID值和名称值填充数据库中的选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆