如何正确检查复选框取决于角色的权限?

时间:2018-03-28 13:01:21

标签: php laravel laravel-blade

我在Laravel应用程序中实现了Laratrust角色系统。现在,我将所有可用角色呈现给超级管理员,以便添加新权限或从特定角色中删除它们。

这是我的AclController

public function index()
{
    $roles = Role::all();
    $permissions = Permission::all();
    $temp = array();

    foreach($permissions as $key => $value) {
        array_push($temp, $value['name']);
    }

    return view('pages.acl.index')->with([ 'roles' => $roles, 'permissions' => $permissions, 'temp' => $temp ]);
}

和我显示权限的.blade模板和复选框:

<div class="tabs-vertical-env">
    <ul class="nav tabs-vertical" style="border-right: 1px solid #ddd;">
        @foreach ($roles as $role)
            <li class="">
                <a href="#{{ $role['name'] }}" data-toggle="tab" aria-expanded="false">{{ $role['display_name'] }}</a>
            </li>
        @endforeach
    </ul>

    <div class="tab-content">
        @foreach ($roles as $role)
            <div class="tab-pane" id="{{ $role['name'] }}">
                @foreach ($permissions as $permission)
                <div class="checkbox checkbox-success">
                        <input type="checkbox" name="{{ $permission['name'] }}" id="{{ $permission['name'] }}" {{ in_array($role->permissions, $temp) ? 'checked' : '' }} />
                        <label for="{{ $permission['name'] }}">
                            {{ $permission['display_name'] }}
                        </label>
                    </div>   
                @endforeach                               
            </div>
        @endforeach
    </div>
</div>

但不幸的是它似乎没有用。什么是解决方法?

1 个答案:

答案 0 :(得分:1)

您的代码应如下所示:

<div class="tabs-vertical-env">
    <ul class="nav tabs-vertical" style="border-right: 1px solid #ddd;">
        @foreach ($roles as $role)
            <li class="">
                <a href="#{{ $role['name'] }}" data-toggle="tab" aria-expanded="false">{{ $role['display_name'] }}</a>
            </li>
        @endforeach
    </ul>

    <div class="tab-content">
        @foreach ($roles as $role)
            <div class="tab-pane" id="{{ $role['name'] }}">
                @foreach ($permissions as $permission)
                    <div class="checkbox checkbox-success">
                        <input 
                                type="checkbox" 
                                name="roles[{{ $role['id'] }}][permissions][{{ $permission['id'] }}]" 
                                id="{{ $role['name'] }}_{{ $permission['name'] }}" 
                                value="{{ $permission['id'] }}" 
                                {{ $role->hasPermission($permission['name']) ? 'checked' : '' }} 
                        />
                        <label for="{{ $role['name'] }}_{{ $permission['name'] }}">
                            {{ $permission['display_name'] }}
                        </label>
                    </div>
                @endforeach
            </div>
        @endforeach
    </div>
</div>