laravel8.5与layuiadmin整合(12)(laravel8. 5 integration with layuiadmin (12))

57.给角色分配权限/app/Http/Controllers/Admin/RoleController.php添加

   /**
     * 编辑角色的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function permission(Request $request, $id) {
        $role = Role::findOrFail($id);
        $permissions = $this->tree();

        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['own'] = $role->hasPermissionTo($item1['id']) ? 'checked' : false ;
            if (isset($item1['_child'])){
                foreach ($item1['_child'] as $key2 => $item2){
                    $permissions[$key1]['_child'][$key2]['own'] = $role->hasPermissionTo($item2['id']) ? 'checked' : false ;
                    if (isset($item2['_child'])){
                        foreach ($item2['_child'] as $key3 => $item3){
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $role->hasPermissionTo($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }

        }

        return view('admin.role.permission',compact('role','permissions'));
    }

    /**
     * 更新角色的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignPermission(Request $request, $id) {
        $role = Role::findOrFail($id);
        $permissions = $request->get('permissions');
        if(empty($permissions)) {
            $role->permissions()->detach();
            return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限1']);
        }else{
            $role->syncPermissions($permissions);
            return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限2']);
        }
    }    
    

58.新增上面的模板/resources/views/admin/role/permission.blade.php

@extends('admin.base')

@section('content')
    <div class="layui-card">
        <div class="layui-card-header layuiadmin-card-header-auto">
            <div class="layui-btn-group ">

                    <button class="layui-btn layui-btn-sm layui-btn-danger" id="listDelete">删 除</button>


                    <a class="layui-btn layui-btn-sm" href="{{ route('admin.permission.create') }}">添 加</a>

                <button class="layui-btn layui-btn-sm" id="returnParent" pid="0">返回上级</button>
            </div>
        </div>
        <div class="layui-card-body">
            <table id="dataTable" lay-filter="dataTable"></table>
            <script type="text/html" id="options">
                <div class="layui-btn-group">

                        <a class="layui-btn layui-btn-sm" lay-event="children">子权限</a>


                        <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>


                        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>

                </div>
            </script>
        </div>
    </div>
@endsection

@section('script')

    <script>
        layui.use(['layer','table','form'],function () {
            var layer = layui.layer;
            var form = layui.form;
            var table = layui.table;
            //用户表格初始化
            var dataTable = table.render({
                elem: '#dataTable'
                ,height: 500
                ,url: "{{ route('admin.permission.data') }}" //数据接口
                ,page: true //开启分页
                ,cols: [[ //表头
                    {checkbox: true,fixed: true}
                    ,{field: 'id', title: 'ID', sort: true,width:80}
                    ,{field: 'name', title: '权限名称'}
                    ,{field: 'display_name', title: '显示名称'}
                    ,{field: 'created_at', title: '创建时间'}
                    ,{field: 'updated_at', title: '更新时间'}
                    ,{fixed: 'right', width: 260, align:'center', toolbar: '#options'}
                ]]
            });

            //监听工具条
            table.on('tool(dataTable)', function(obj){ //注:tool是工具条事件名,dataTable是table原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    ,layEvent = obj.event; //获得 lay-event 对应的值
                if(layEvent === 'del'){
                    layer.confirm('确认删除吗?', function(index){
                        $.post("{{ route('admin.permission.destroy') }}",{_method:'delete',ids:[data.id]},function (result) {
                            if (result.code==0){
                                obj.del(); //删除对应行(tr)的DOM结构
                            }
                            layer.close(index);
                            layer.msg(result.msg,{icon:6})
                        });
                    });
                } else if(layEvent === 'edit'){
                    location.href = '/admin/permission/'+data.id+'/edit';
                } else if (layEvent === 'children'){
                    var pid = $("#returnParent").attr("pid");
                    if (data.parent_id!=0){
                        $("#returnParent").attr("pid",pid+'_'+data.parent_id);
                    }
                    dataTable.reload({
                        where:{model:"permission",parent_id:data.id},
                        page:{curr:1}
                    })
                }
            });

            //按钮批量删除
            $("#listDelete").click(function () {
                layer.msg("由于权限重要性,系统已禁止批量删除",{icon:5});
            });
            //返回上一级
            $("#returnParent").click(function () {
                var pid = $(this).attr("pid");
                if (pid!='0'){
                    ids = pid.split('_');
                    parent_id = ids.pop();
                    $(this).attr("pid",ids.join('_'));
                }else {
                    parent_id=pid;
                }
                dataTable.reload({
                    where:{model:"permission",parent_id:parent_id},
                    page:{curr:1}
                })
            })
        })
    </script>

@endsection

59.开发给用户角色和权限,路由添加

// 系统管理
Route::group(['prefix' => 'admin','middleware' => 'auth'],function() {
    //
    // 给人员分配角色
    Route::get('user/{id}/role',[App\Http\Controllers\Admin\UserController::class, 'role'])
        ->name('admin.user.role');
    Route::put('user/{id}/assignRole',[App\Http\Controllers\Admin\UserController::class, 'assignRole'])
        ->name('admin.user.assignRole');
    // 给人员分配权限
    Route::get('user/{id}/permission',[App\Http\Controllers\Admin\UserController::class, 'permission'])
        ->name('admin.user.permission');
    Route::put('user/{id}/assignPermission',[App\Http\Controllers\Admin\UserController::class, 'assignPermission'])
        ->name('admin.user.assignPermission');

});
    

60.添加角色模型/app/Models/Role.php

namespace App\Models;

class Role extends \Spatie\Permission\Models\Role {

}

61.添加角色关联/app/Models/User.php添加 HasRoles,如下

class User extends Authenticatable
{    
    //
    use HasApiTokens, HasFactory, Notifiable, HasRoles;
    //
}

62.控制器添加方法/app/Http/Controllers/Admin/UserController.php

    /**
     * 获取用户的角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function role(Request $request, $id) {
        $user = User::findOrFail($id);
        $roles = Role::get();
        foreach ($roles as $role) {
            $role->own = $user->hasRole($role) ? true : false;
        }
        return view('admin.user.role',compact('roles','user'));
    }

    /**
     * 处理编辑用户后的角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignRole(Request $request, $id) {
        $user = User::findOrFail($id);
        $roles = $request->get('roles',[]);
        if($user->syncRoles($roles)) {
            return redirect()->to(route('admin.user'))->with(['status'=>'更新用户角色成功']);
        }
        return redirect()->to(route('admin.user'))->withErrors(['status'=>'系统错误']);

    }

    /**
     * 获取用户拥有的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function permission(Request $request, $id) {
        $user = User::findOrFail($id);
        $permissions = $this->tree();
        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['own'] = $user->hasDirectPermission($item1['id']) ? 'checked' : false ;
            if (isset($item1['_child'])){
                foreach ($item1['_child'] as $key2 => $item2){
                    $permissions[$key1]['_child'][$key2]['own'] = $user->hasDirectPermission($item2['id']) ? 'checked' : false ;
                    if (isset($item2['_child'])){
                        foreach ($item2['_child'] as $key3 => $item3){
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $user->hasDirectPermission($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }
        }
        return view('admin.user.permission',compact('user','permissions'));
    }

    /**
     * 处理编辑用户的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignPermission(Request $request, $id) {
        $user = User::findOrFail($id);
        $permissions = $request->get('permissions');

        if (empty($permissions)){
            $user->permissions()->detach();
            return redirect()->to(route('admin.user'))->with(['status'=>'已更新用户直接权限']);
        }
        $user->syncPermissions($permissions);
        return redirect()->to(route('admin.user'))->with(['status'=>'已更新用户直接权限']);
    }
    
————————

57.给角色分配权限/app/Http/Controllers/Admin/RoleController.php添加

   /**
     * 编辑角色的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function permission(Request $request, $id) {
        $role = Role::findOrFail($id);
        $permissions = $this->tree();

        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['own'] = $role->hasPermissionTo($item1['id']) ? 'checked' : false ;
            if (isset($item1['_child'])){
                foreach ($item1['_child'] as $key2 => $item2){
                    $permissions[$key1]['_child'][$key2]['own'] = $role->hasPermissionTo($item2['id']) ? 'checked' : false ;
                    if (isset($item2['_child'])){
                        foreach ($item2['_child'] as $key3 => $item3){
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $role->hasPermissionTo($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }

        }

        return view('admin.role.permission',compact('role','permissions'));
    }

    /**
     * 更新角色的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignPermission(Request $request, $id) {
        $role = Role::findOrFail($id);
        $permissions = $request->get('permissions');
        if(empty($permissions)) {
            $role->permissions()->detach();
            return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限1']);
        }else{
            $role->syncPermissions($permissions);
            return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限2']);
        }
    }    
    

58.新增上面的模板/resources/views/admin/role/permission.blade.php

@extends('admin.base')

@section('content')
    <div class="layui-card">
        <div class="layui-card-header layuiadmin-card-header-auto">
            <div class="layui-btn-group ">

                    <button class="layui-btn layui-btn-sm layui-btn-danger" id="listDelete">删 除</button>


                    <a class="layui-btn layui-btn-sm" href="{{ route('admin.permission.create') }}">添 加</a>

                <button class="layui-btn layui-btn-sm" id="returnParent" pid="0">返回上级</button>
            </div>
        </div>
        <div class="layui-card-body">
            <table id="dataTable" lay-filter="dataTable"></table>
            <script type="text/html" id="options">
                <div class="layui-btn-group">

                        <a class="layui-btn layui-btn-sm" lay-event="children">子权限</a>


                        <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>


                        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>

                </div>
            </script>
        </div>
    </div>
@endsection

@section('script')

    <script>
        layui.use(['layer','table','form'],function () {
            var layer = layui.layer;
            var form = layui.form;
            var table = layui.table;
            //用户表格初始化
            var dataTable = table.render({
                elem: '#dataTable'
                ,height: 500
                ,url: "{{ route('admin.permission.data') }}" //数据接口
                ,page: true //开启分页
                ,cols: [[ //表头
                    {checkbox: true,fixed: true}
                    ,{field: 'id', title: 'ID', sort: true,width:80}
                    ,{field: 'name', title: '权限名称'}
                    ,{field: 'display_name', title: '显示名称'}
                    ,{field: 'created_at', title: '创建时间'}
                    ,{field: 'updated_at', title: '更新时间'}
                    ,{fixed: 'right', width: 260, align:'center', toolbar: '#options'}
                ]]
            });

            //监听工具条
            table.on('tool(dataTable)', function(obj){ //注:tool是工具条事件名,dataTable是table原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    ,layEvent = obj.event; //获得 lay-event 对应的值
                if(layEvent === 'del'){
                    layer.confirm('确认删除吗?', function(index){
                        $.post("{{ route('admin.permission.destroy') }}",{_method:'delete',ids:[data.id]},function (result) {
                            if (result.code==0){
                                obj.del(); //删除对应行(tr)的DOM结构
                            }
                            layer.close(index);
                            layer.msg(result.msg,{icon:6})
                        });
                    });
                } else if(layEvent === 'edit'){
                    location.href = '/admin/permission/'+data.id+'/edit';
                } else if (layEvent === 'children'){
                    var pid = $("#returnParent").attr("pid");
                    if (data.parent_id!=0){
                        $("#returnParent").attr("pid",pid+'_'+data.parent_id);
                    }
                    dataTable.reload({
                        where:{model:"permission",parent_id:data.id},
                        page:{curr:1}
                    })
                }
            });

            //按钮批量删除
            $("#listDelete").click(function () {
                layer.msg("由于权限重要性,系统已禁止批量删除",{icon:5});
            });
            //返回上一级
            $("#returnParent").click(function () {
                var pid = $(this).attr("pid");
                if (pid!='0'){
                    ids = pid.split('_');
                    parent_id = ids.pop();
                    $(this).attr("pid",ids.join('_'));
                }else {
                    parent_id=pid;
                }
                dataTable.reload({
                    where:{model:"permission",parent_id:parent_id},
                    page:{curr:1}
                })
            })
        })
    </script>

@endsection

59. Develop user roles and permissions, and add routes

// 系统管理
Route::group(['prefix' => 'admin','middleware' => 'auth'],function() {
    //
    // 给人员分配角色
    Route::get('user/{id}/role',[App\Http\Controllers\Admin\UserController::class, 'role'])
        ->name('admin.user.role');
    Route::put('user/{id}/assignRole',[App\Http\Controllers\Admin\UserController::class, 'assignRole'])
        ->name('admin.user.assignRole');
    // 给人员分配权限
    Route::get('user/{id}/permission',[App\Http\Controllers\Admin\UserController::class, 'permission'])
        ->name('admin.user.permission');
    Route::put('user/{id}/assignPermission',[App\Http\Controllers\Admin\UserController::class, 'assignPermission'])
        ->name('admin.user.assignPermission');

});
    

60. Add role model / APP / Models / role php

namespace App\Models;

class Role extends \Spatie\Permission\Models\Role {

}

61. Add role Association / APP / Models / user Add hasroles to PHP as follows

class User extends Authenticatable
{    
    //
    use HasApiTokens, HasFactory, Notifiable, HasRoles;
    //
}

62.控制器添加方法/app/Http/Controllers/Admin/UserController.php

    /**
     * 获取用户的角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function role(Request $request, $id) {
        $user = User::findOrFail($id);
        $roles = Role::get();
        foreach ($roles as $role) {
            $role->own = $user->hasRole($role) ? true : false;
        }
        return view('admin.user.role',compact('roles','user'));
    }

    /**
     * 处理编辑用户后的角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignRole(Request $request, $id) {
        $user = User::findOrFail($id);
        $roles = $request->get('roles',[]);
        if($user->syncRoles($roles)) {
            return redirect()->to(route('admin.user'))->with(['status'=>'更新用户角色成功']);
        }
        return redirect()->to(route('admin.user'))->withErrors(['status'=>'系统错误']);

    }

    /**
     * 获取用户拥有的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function permission(Request $request, $id) {
        $user = User::findOrFail($id);
        $permissions = $this->tree();
        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['own'] = $user->hasDirectPermission($item1['id']) ? 'checked' : false ;
            if (isset($item1['_child'])){
                foreach ($item1['_child'] as $key2 => $item2){
                    $permissions[$key1]['_child'][$key2]['own'] = $user->hasDirectPermission($item2['id']) ? 'checked' : false ;
                    if (isset($item2['_child'])){
                        foreach ($item2['_child'] as $key3 => $item3){
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $user->hasDirectPermission($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }
        }
        return view('admin.user.permission',compact('user','permissions'));
    }

    /**
     * 处理编辑用户的权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignPermission(Request $request, $id) {
        $user = User::findOrFail($id);
        $permissions = $request->get('permissions');

        if (empty($permissions)){
            $user->permissions()->detach();
            return redirect()->to(route('admin.user'))->with(['status'=>'已更新用户直接权限']);
        }
        $user->syncPermissions($permissions);
        return redirect()->to(route('admin.user'))->with(['status'=>'已更新用户直接权限']);
    }