Laravel:如何获取与模型绑定的选择(下拉列表)的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22003063/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:05:37  来源:igfitidea点击:

Laravel: How get the value of a select (Drop-Down Lists) to bind with the model?

phplaravel

提问by Emiliano

something like... in the view

像......在视图中

{{Form::open(array('url'=>'expense/add', 'method' => 'POST', 'class' => 'form-signin'), array('role'=>'form'))}}
      <select id="expense_category_id" class="form-control">
      @foreach($data['categories'] as $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
      @endforeach
    {{Form::submit('submit', array('class'=>'btn btn-lg btn-primary btn-block'))}}
  {{Form::close()}}

回答by olgundutkan

Controller:

控制器:

$data['categories'] = Category::lists('name', 'id');

If you are using the attributeCategory model controller:

如果您使用的是属性Category 模型控制器:

$data['categories'] = Category::get()->lists('name', 'id');

view:

看法:

{{ Form::select('expense_category_id', $data['categories'], null, array('class' => 'form-control') }}

For laravel5.3 use pluck.

对于 laravel5.3 使用 pluck。

$data['categories'] = Category::all()->pluck('name', 'id');Reference

$data['categories'] = Category::all()->pluck('name', 'id');参考

You can try.

你可以试试。

回答by kipzes

Or you can pass the categories from your controller like this:

或者您可以像这样从控制器传递类别:

$categories = Category::all();

And inside your blade generate the dropdown like this:

在你的刀片内部生成这样的下拉菜单:

{!! Form::select('category', $categories->lists('name', 'id'), Input::old('category'), ['class' => 'form-control']) !!}