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'] ) }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了