ds08541 2017-09-19 10:02
浏览 38
已采纳

更改Laravel 5.4中的起始选择值

I'm using Laravel 5.4 and i'm trying to make select form with this code:

{{ Form::select('country', App\Countries::all()->pluck('en_title'), old('country', $user->country), array('class' => 'form-control') ) }}

The result that i'm receiving is this:

<select name="country" class="form-control">
     <option value="0">a</option>
     <option value="1">b</option>
     <option value="2">c</option>
     <option value="3">d</option>
     ...
</select>

The problem is that i don't have in the database value 0, so i want to start from value="1" like:

<select name="country" class="form-control">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
     <option value="4">d</option>
     ...
</select>

What should i change? I read everything possible, but no one try to do this with the specific function, or this is impossible with this function?

  • 写回答

1条回答 默认 最新

  • drn9573 2017-09-19 11:05
    关注

    You can specify the key when you pluck. In your case it'd be

    {{ Form::select('country', App\Countries::all()->pluck('en_title', 'id'), old('country', $user->country), array('class' => 'form-control') ) }}
    

    Which would result in an array such as

    [1 => 'United Kingdom', 2 => 'United States']
    

    Where the key is the ID of the country.

    In addition to the above, you're selecting all then plucking the data you want from the resulting data set. You can use pluck in place of all which builds a select for you and just grabs the relevant fields. For example

    App\Countries::pluck('en_title', 'id')
    

    Also, on a side note you should probably create that list of countries in your controller rather than calling your database in your views. It'd simplify the code in your view as well as generally being better practice

    // Controller 
    $countries = \App\Countries::pluck('en_title', 'id');
    
    return view('viewname')->withCountries($countries);
    
    // View
    
    {{ Form::select('country', $countries, old('country', $user->country), ['class' => 'form-control'] ) }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳