duankao4489 2016-09-29 11:49
浏览 50
已采纳

Laravel从员工表下的相关表中呈现下拉列表

I have 2 tables. Employee table and Roles tables. In my employee.show blade I want to render the dropdown list of the role already assgined or available to assign. I am not using collective forms and am a little stuck as all tutorials use thse.

My controller

 public function show($employee)
 {
     $employee = Employees::find($employee); 
     $roles = Roles::pluck('role_name', 'id'); 
 return view('employees.show')->withEmployee($employee)->withRoles($roles);
}

and my show.blade. Question is how do i pull the complete list from db of all other roles so a user can update?

   <div class="form-group">
<label class="col-md-4 control-label" for="roles_id">Role</label>
<div class="col-md-4">
<select id="roles_id" name="roles_id" class="form-control">
<option value="{{ $employee->roles->id }}">{{ $employee->roles->role_name }}</option>
</select>            
</div>
</div>
  • 写回答

1条回答 默认 最新

  • duanlie1298 2016-09-29 12:27
    关注

    What you've done in your controller seems correct. Your view however should loop through the roles and create options for them. Bear in mind, that you've used Role::pluck('role_name', 'id'), which will return an array of 'id' => 'role_name'.

    You can decide which one is selected by adding a selected attribute to the employee's role option by using a ternary statement, which compare's the employee's role_id to the role_id we're currently looking at in the loop.

    Try something like this:

    <select name="roles_id">
        <option value="">Select...</option>
        @foreach ($roles as $roleId => $roleName)
            <option value="{{ $roleId }}"{!! $employee->role_id == $roleId ? ' selected' : '' !!}>{{ $roleName }}</option>
        @endforeach
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line