如何使用 Laravel 在下拉列表中显示数据库中的选定值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50970020/
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
How to show selected value from database in dropdown using Laravel?
提问by Sarita Sharma
I want to show selected value from database into dropdown list on page load.
我想在页面加载时将数据库中的选定值显示到下拉列表中。
My controller index function is :
我的控制器索引功能是:
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
数据库中高度的列名是:高度
My dropdown in profile_update.blade.php is
我在 profile_update.blade.php 的下拉菜单是
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
@foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
@endforeach</select>
回答by Márcio Winicius
This is a example of how I do this:
这是我如何执行此操作的示例:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
@foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
@endforeach
</select>
回答by Adam W?do?kowski
@Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd
e.g.
@Sarita Sharma 显示错误。也许那时有人会帮你解决这个问题。在控制器的集合中显示数据 - 使用dd
例如
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
您想在视图中使用 profile_data 中的适当高度值显示国家/地区吗?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
附言。代码怎么放,请使用格式化代码——将代码放在``中,值名称中使用camelCase(保持良好的PSR-1实践)——更容易阅读代码。