抱歉回复晚了
显然lists 方法在 Laravel 中已经是 deprecated,但是你可以使用 pluck 方法。
例如:
Laravel 5.7
public function create()
{
$countries = Country::pluck('country_name','id');
return View::make('test.new')->with('countries', $countries);
}
如果您是 FORM 组件,则在视图中传递为
{{ Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}
如果会生成下拉菜单
但我有一种情况表明选择国家作为第一个选项并作为空值
<option value="" selected="selected">--Select Country--</option>
所以我提到了
https://stackoverflow.com/a/51324218/8487424
并修复了这个问题,但以后如果我想更改它,我讨厌在视图中更改它
所以已经创建了基于https://stackoverflow.com/a/51324218/8487424的辅助函数并放在Country Model中
public static function toDropDown($tableName='',$nameField='',$idField='',$defaultNullText='--Select--')
{
if ($idField == null)
{
$idField="id";
}
$listFiledValues = DB::table($tableName)->select($idField,$nameField)->get();
$selectArray=[];
$selectArray[null] = $defaultNullText;
foreach ($listFiledValues as $listFiledValue)
{
$selectArray[$listFiledValue->$idField] = $listFiledValue->$nameField;
}
return $selectArray;
}
在控制器中
public function create()
{
$countries = Country::toDropDown('countries','name','id','--Select Country--');
return View::make('test.new')->with('countries', $countries);
}
终于在视图中
{{ Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}
结果如预期,但我强烈建议使用pluck()方法