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

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

  1. <fieldset>
  2. <legend>Groups</legend>
  3. @foreach($roles as $role)
  4. {!! Form::checkbox($role->field) !!} <span>{{ $role->name }}</span><br>
  5. @endforeach
  6. </fieldset>

This results in the following being produced:

  1. [] Administrator
  2. [] Supervisor
  3. [] Employer
  4. [] Contractor

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

  1. /**
  2. * Get all user roles.
  3. *
  4. * @param $id
  5. * @return Collection
  6. */
  7. public function getUsersRoles($id)
  8. {
  9. return $this->roleUser->where('user_id', $id)->get();
  10. }

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 01: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部