[英]laravel 5.4 form dropdown from database
I want to fetch drop down option value & name from database, to do that my controller code is 我想从数据库中获取下拉选项值和名称,为此我的控制器代码是
$roles = Role::pluck('role','user_id');
return view('users.add_role',compact('roles'));
to fetch this data from drop down list my view file code is 从下拉列表中获取此数据我的视图文件代码是
<select name="role" class="form-control" >
@foreach($roles as $role)
<option value="{{ $role->user_id }} "> {{ $role->role }} </option>
@endforeach
</select>
but it says error 但它说错误
Trying to get property of non-object (View: C:\xampp\htdocs\auth2\resources\views\users\add_role.blade.php)
if i just only use 如果我只是使用
<select name="role" class="form-control" >
@foreach($roles as $role)
<option value="{{ $role }} "> {{ $role }} </option>
@endforeach
</select>
then it shows role column of the table, but it not pass option value to database. 然后它显示表的角色列,但它不将选项值传递给数据库。 so what is the correct way to generate option value & name from database?
那么从数据库生成选项值和名称的正确方法是什么?
Your $roles
variable containt an array which is looks like 你的
$roles
变量包含一个看起来像的数组
[0] => 'your_role'
[1] => 'your_role'
Where is 0 and 1 index is user_id. 0和1索引在哪里是user_id。 So your
user_id
is set as an index of your $roles
array. 因此,您的
user_id
被设置为$roles
数组的索引。 Simply do it dd($roles)
and check the output. 只需执行
dd($roles)
并检查输出。 $key as $role will work. $ key作为$ role将起作用。 Where $key will containt the
user_id
. 其中$ key将包含
user_id
。
@foreach($roles as $key => $role)
<option value="{{ $key }} "> {{ $role }} </option>
@endforeach
I use laravel collective package to generate dropdown list much more easier, you can do things like, on your blade template and it will render the list for you 我使用laravel集合包来生成下拉列表更加容易,你可以在你的刀片模板上做一些事情,它会为你呈现列表
{{ Form::select('role', $role )) }} {{Form :: select('role',$ role))}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.