laravel 使用数据库中的值在下拉列表中显示所选值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43997294/
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
Displaying selected value in a drop down with values from the database
提问by Sandeesh
I have a drop down that i am populating from the database with this method
我有一个下拉列表,我使用这种方法从数据库中填充
public function view($id)
{
$id = request()->segment(2);
$items = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser', compact('items'));
}
I am then displaying the select box this way in the database
然后我在数据库中以这种方式显示选择框
<select name="user_role" class="form-control">
@foreach($items as $item)
<option value="{{$item->name}}">{{$item->display_name}}</option>
@endforeach
</select>
The select box generated is being used during the creation of a record. However, i now want to edit the form and i want to mark as selected the option saved in the database.
在创建记录期间正在使用生成的选择框。但是,我现在想要编辑表单,并且想要将保存在数据库中的选项标记为选中。
Before when i knew the name
and display_name
i could easily do this
在我知道name
并且display_name
我可以轻松做到这一点之前
<option value="admin" @if ($role->name == "admin")selected="selected" @endif>Admin</option>
<option value="user" @if ($role->name == "user")selected="selected" @endif>User</option>
<option value="superuser" @if ($role->name == "superuser")selected="selected" @endif>Superuser</option>
How can i mark as selected the saved value in the database?.
如何将数据库中保存的值标记为选中?
This is the roles table
这是角色表
This is the role user table
这是角色用户表
回答by Sandeesh
Controller
控制器
$currentRole = Ru::where('user_id','=',Auth::id())->first();
$roles = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser', compact('roles', 'currentRole'));
View
看法
<select name="user_role" class="form-control">
@foreach($roles as $role)
<option value="{{$role->name}}" {{ $role->name === $currentRole->name? 'selected' : '' }}>{{$role->display_name}}</option>
@endforeach
</select>
By the way, you shouldn't have a model for your pivot table. You need to use relationships to access the data. With proper relationship setup, you can do something like this.
顺便说一句,您不应该为数据透视表创建模型。您需要使用关系来访问数据。通过适当的关系设置,你可以做这样的事情。
$currentRole = auth()->user()->role
回答by Onix
Your logic is not correct, you have the roles as records in the database... Instead you should have a table users with a field role and maybe link it to the role table. And select the saved value from the user table not the role table...
您的逻辑不正确,您将角色作为数据库中的记录......相反,您应该有一个具有字段角色的表用户,并且可能将其链接到角色表。并从用户表而不是角色表中选择保存的值...
Read more about how to build One-to-One Relationships here