Laravel 选择模型的名称和 id 并在 SelectBox 中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39616054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Select Name and id of Model and use in SelectBox
提问by Scarwolf
This is my current Function in my Controller:
这是我在控制器中的当前功能:
public function addProduct()
{
$categories = Category::all();
return view('admin.products.add')->with('categories', $categories);
}
I want to only select the columns "name" and "id" from the Category Model and assign them to the selectbox in my view like this:
我只想从类别模型中选择列“name”和“id”,并将它们分配给我视图中的选择框,如下所示:
<select>
<option value="ID">NAME</option>
</select>
How can I do this using the Form
-Facade?
如何使用Form
-Facade执行此操作?
回答by Filip Koblański
try with pluck
method from the laravel Collection
:
尝试使用pluck
laravel 中的方法Collection
:
$categories = Category::all()->pluck('name', 'id');
and then in the view:
然后在视图中:
{!! Form::select('name', $categories) !!}
回答by Komal
Try this generate all category
试试这个生成所有类别
<select name="category" class="form-control">
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>
And if you want to set particular category selected then do this
如果您想设置选定的特定类别,请执行此操作
<select name="category" class="form-control">
@foreach($categories as $category)
<option value="{{ $category->id }}" <?php if($hotel->category_id == $category->id) { echo "selected";}?>>{{ $category->name }}</option>
@endforeach
</select>
回答by Ganesh
Lists was deprecated in L5.2 and removed on L5.3
列表在 L5.2 中被弃用并在 L5.3 中被移除
Try this, simple & neat.
试试这个,简单而整洁。
$categories = Category::lists('name', 'id');
{!! Form::select('categories[]', $categories, null, [
'class' => 'form-control', 'multiple'
]) !!}
回答by Francisunoxx
You can use foreach here
您可以使用 foreach here
In your blade view.
在您的刀片视图中。
<select name = "category[]">
@foreach($categories as $category)
<option value = "{{$category->id}}">{{$category->youValueHere}}></option>
@endforeach
</select>