duanbei1598 2015-09-07 09:16
浏览 52
已采纳

Laravel从数据库中预先选择复选框字段的最佳方法

I am building an app that has users and roles. I want users with the Administrator role to be able to change other user roles. For example add/remove them from other roles.

To do this, I have setup a form with checkboxes, which lists out all of the user roles available:

View

<fieldset>
    <legend>Groups</legend>
    @foreach($roles as $role)
        {!! Form::checkbox($role->field) !!} <span>{{ $role->name }}</span><br>
    @endforeach
</fieldset>

This results in the following being produced:

[] Administrator
[] Supervisor
[] Employer
[] Contractor

I have a method which I use to load roles that the user belongs to:

/**
 * Get all user roles.
 *
 * @param $id
 * @return Collection
 */
public function getUsersRoles($id)
{
    return $this->roleUser->where('user_id', $id)->get();
}

The above method returns an object containing each role.

How can I use this method to pre-select roles which the user belongs to on my view?

  • 写回答

1条回答 默认 最新

  • dongqichang7988 2015-09-07 09:28
    关注
    {!! Form::checkbox($role->field->name, $role->field->id, in_array($role->id, Auth::user()->getUsersRoles()->lists('id'))) !!}
    

    You check if the current role id is inside your available user roles. If true the box will be selected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度