如何修改Role & Permission表格代码实现目标权限列表样式?
角色权限列表表格样式修改方案
问题说明
你需要实现模块对应Show/Create/Edit/Delete权限开关的表格布局,原代码因循环逻辑错误导致列结构混乱,无法匹配预期样式。
修改后代码
控制器层(权限分组)
先在控制器中对权限按模块分组,确保每个模块对应一行数据:
// 假设Permission是你的权限模型 $permissions = \App\Models\Permission::all()->groupBy('module'); $rolePermissions = // 保留你原有获取角色已拥有权限ID集合的逻辑即可
视图层(表格结构)
替换原有表格代码为以下结构:
<table class="table"> <thead> <tr> <th scope="col">Module</th> <th scope="col">Show</th> <th scope="col">Create</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> @foreach ($permissions as $moduleName => $modulePermissions) <tr> <!-- 模块名称列 --> <td>{{ $moduleName }}</td> <!-- Show权限开关 --> <td> @php // 匹配该模块的Show权限,需根据你的权限命名规则调整 $showPermission = $modulePermissions->where('name', 'show-' . strtolower($moduleName))->first(); @endphp @if($showPermission) <div class="form-check form-switch"> <input class="form-check-input" name="permission[]" type="checkbox" role="switch" value="{{ $showPermission->id }}" {{ in_array($showPermission->id, $rolePermissions) ? 'checked' : '' }}> </div> @endif </td> <!-- Create权限开关 --> <td> @php $createPermission = $modulePermissions->where('name', 'create-' . strtolower($moduleName))->first(); @endphp @if($createPermission) <div class="form-check form-switch"> <input class="form-check-input" name="permission[]" type="checkbox" role="switch" value="{{ $createPermission->id }}" {{ in_array($createPermission->id, $rolePermissions) ? 'checked' : '' }}> </div> @endif </td> <!-- Edit权限开关 --> <td> @php $editPermission = $modulePermissions->where('name', 'edit-' . strtolower($moduleName))->first(); @endphp @if($editPermission) <div class="form-check form-switch"> <input class="form-check-input" name="permission[]" type="checkbox" role="switch" value="{{ $editPermission->id }}" {{ in_array($editPermission->id, $rolePermissions) ? 'checked' : '' }}> </div> @endif </td> <!-- Delete权限开关 --> <td> @php $deletePermission = $modulePermissions->where('name', 'delete-' . strtolower($moduleName))->first(); @endphp @if($deletePermission) <div class="form-check form-switch"> <input class="form-check-input" name="permission[]" type="checkbox" role="switch" value="{{ $deletePermission->id }}" {{ in_array($deletePermission->id, $rolePermissions) ? 'checked' : '' }}> </div> @endif </td> </tr> @endforeach </tbody> </table>
关键调整点
- 数据分组:通过
groupBy('module')将同模块的权限归为一组,保证表格每行对应一个模块 - 列结构对齐:让tbody的列数与thead完全匹配,每行固定5列(模块+4个权限)
- 权限匹配逻辑:根据你的权限命名规则(示例为
操作-模块名),精准定位每个模块对应的权限项,生成开关 - 容错处理:通过
@if($permission)判断权限是否存在,避免空内容导致的布局错乱
注意事项
如果你的权限命名规则不是操作-模块名(比如是module.operation格式),需要修改where('name', ...)中的匹配条件,确保能正确找到对应权限。
内容的提问来源于stack exchange,提问作者vandan makwana
相关产品推荐
相关产品推荐

