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
<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
答案 0 :(得分:1)
控制器
$currentRole = Ru::where('user_id','=',Auth::id())->first();
$roles = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser', compact('roles', 'currentRole'));
查看
<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>
顺便说一句,你不应该有你的数据透视表的模型。您需要使用关系来访问数据。通过正确的关系设置,您可以执行类似的操作。
$currentRole = auth()->user()->role
答案 1 :(得分:0)
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