laravel--通用后台管理系统--添加菜单--角色添加权限--根据用户权限显示菜单
程序员文章站
2022-05-16 21:58:53
...
学习总结
1.layui中的form.render()
方法在使用过程中,只能渲染2次,问题在角色权限的添加和修改,全选和一级菜单只能选中和取消只能使用一次,第2次点击就不能渲染到复选框上了
2.在权限中间件RightsVerify.php
中为Request对象添加rights属性,在Home控制器中使用whereIn()
方法查找符合当前用户的权限菜单。
**问题**
使用form.render()方法无法连续渲染复选框,实现复选框菜单联动
**解决方法
不使用layui中的form.render()方法,使用jquery实现渲染$('input[type="checkbox"]~div').addClass('layui-form-checked');
因为美化后的复选框是一个div,并且和input的checkbox在同一个大的div中,所以使用同级选择器,选中美化后的div,然后添加css样式。
1.菜单控制器Menu.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;//哈希密码加密
use Illuminate\Http\Request;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//后台菜单管理控制器
class Menus extends Controller
{
//菜单列表
public function index(Request $req)
{
$pid =(int)$req->pid;
if($pid):
//找到菜单的上一级菜单
$res['pMenu']=DB::table('admin_menu')->select('mid','pid','title')->where('mid',$pid)->item();
else:
$res['pMenu']['mid']=0;
endif;
$res['menus']=DB::table('admin_menu')->where('pid',$pid)->lists();
return view('/admins/menus/index',$res);
// echo '<pre>';
// print_r($res);
// exit;
}
//添加菜单
public function add(Request $req)
{
$res['pid'] = $req->pid;
return view('/admins/menus/add',$res);
}
//保存菜单
public function save(Request $req)
{
$mid =(int) $req->mid;
//如果mid为0,代表是添加,否则代表是修改
//菜单的pid,上一级菜单的id
$data['pid'] =(int) $req->pid;
//判断菜单名称是否为空
if(trim($req->title)===''):
return json_encode(['status'=>'1','msg'=>'菜单名称不能为空']);
endif;
$data['title'] = trim($req->title);
//如果ishidden='on',正常显示的菜单
if($req->ishidden):
$data['ishidden'] = (int)'0';//代表正常显示菜单
else:
$data['ishidden'] = (int)'1';//代表隐藏菜单
endif;
//排序
$data['ord'] =(int)$req->ord;
//判断是否输入控制器
if(trim($req->controller)===''):
return json_encode(['status'=>'1','msg'=>'控制器名称不能为空']);
endif;
$data['controller'] = trim($req->controller);
//控制器方法
$data['action'] = trim($req->action);
if($mid):
$res = DB::table('admin_menu')->where('mid',$mid)->update($data);
else:
$res = DB::table('admin_menu')->insert($data);
endif;
if($res):
return json_encode(['status'=>'0','msg'=>'保存成功']);
else:
return json_encode(['status'=>'1','msg'=>'保存失败']);
endif;
}
public function del(Request $req)
{
$mid = $req->mid;
$res = DB::table('admin_menu')->where('mid',$mid)->delete();
if($res)
{
return json_encode(['status'=>'0','msg'=>'删除成功']);
}
else
{
return json_encode(['status'=>'1','msg'=>'删除失败']);
}
}
public function edit(Request $req)
{
$mid = $req->mid;
$res['menu'] = DB::table('admin_menu')->where('mid',$mid)->item();
return view('/admins/menus/edit',$res);
}
}
1.1菜单列表的显示index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>菜单管理</title>
</head>
<style>
.addBtn {
margin-top: 10px;
width: 120px;
margin-left: auto;
margin-right: 50px;
}
.pMenuBtn {
margin-left: 10px;
}
.layui-table {
width: 95%;
margin: 20px;
}
</style>
<body>
<div class="addBtn">
<button class="layui-btn" onclick="add({{$pMenu['mid']}})">添加菜单</button>
</div>
@if($pMenu['mid'])
<div class="pMenuBtn">
<button class="layui-btn layui-btn-primary" onclick="back({{$pMenu['pid']}})">返回『{{$pMenu['title']}}』菜单</button>
</div>
@endif
<table class="layui-table">
<thead>
<tr>
<th>MID</th>
<th>菜单名称</th>
<th>是否隐藏</th>
<th>排序</th>
<th>controller</th>
<th>action</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach($menus as $menu)
<tr>
<td>{{$menu['mid']}}</td>
<td>{{$menu['title']}}</td>
<td>{{$menu['ishidden']?'是':'否'}}</td>
<td>{{$menu['ord']}}</td>
<td>{{$menu['controller']}}</td>
<td>{{$menu['action']}}</td>
<td>
<button class="layui-btn layui-btn-xs layui-btn-primary"
onclick="child({{$menu['mid']}})">下级菜单</button>
<button class="layui-btn layui-btn-xs" onclick="edit({{$menu['mid']}})">修改</button>
<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="del({{$menu['mid']}})">删除</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
<script>
layui.use(['layer'], function() {
layer = layui.layer;
$ = layui.jquery;
});
//显示下级菜单
function child(id) {
window.location.href = '/admins/menus/index?pid=' + id;
}
//返回上级菜单
function back(id) {
window.location.href = '/admins/menus/index?pid=' + id;
}
//添加菜单
function add(pid) {
//iframe层
layer.open({
type: 2,
title: '添加菜单',
shadeClose: true,
shade: 0.8,
area: ['380px', '80%'],
content: '/admins/menus/add?pid=' + pid, //iframe的url
btn: ['保存'],
yes: function(index, layero) {
//得到iframe页的窗口对象,执行iframe页的方法:iframeWin.子页面的方法名称();
var iframeWin = window[layero.find('iframe')[0]['name']];;
iframeWin.save();
}
});
}
//修改菜单
function edit(id) {
//iframe层
layer.open({
type: 2,
title: '修改菜单',
shadeClose: true,
shade: 0.8,
area: ['380px', '80%'],
content: '/admins/menus/edit?mid=' + id, //iframe的url
btn: ['保存'],
yes: function(index, layero) {
//得到iframe页的窗口对象,执行iframe页的方法:iframeWin.子页面的方法名称();
var iframeWin = window[layero.find('iframe')[0]['name']];;
iframeWin.save();
}
});
}
//删除菜单
function del(id) {
layer.confirm('确认要删除菜单吗?', function() {
$.get('/admins/menus/del?mid=' + id, function(res) {
if (res.status > 0) {
layer.alert(res.msg, {
icon: 2
});
} else {
layer.msg(res.msg, {
time: 3000
});
window.location.reload();
}
}, 'json');
});
}
</script>
</html>
- 一级菜单
- 一级菜单下的子菜单
1.2 添加菜单add.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>添加菜单</title>
<style>
.layui-form {
margin-top: 20px;
margin-right: 20px;
}
</style>
</head>
<body>
<form action="" class="layui-form">
@csrf
<input type="hidden" name="pid" value="{{$pid}}">
<div class="layui-form-item">
<label for="" class="layui-form-label">菜单名称</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="title">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">是否隐藏</label>
<div class="layui-input-inline">
<input type="checkbox" name="ishidden" lay-skin='switch' lay-text='正常|隐藏'>
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">排序</label>
<div class="layui-input-inline">
<input type="number" class="layui-input" name="ord" value="0">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">controller</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="controller">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">action</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="action">
</div>
</div>
</form>
</body>
<script>
layui.use(['form', 'layer'], function() {
var form = layui.form;
var layer = layui.layer;
$ = layui.jquery;
});
//在父窗口中调用了save方法
function save() {
if ($('input[name="title"]').val().trim() === '') {
error('请输入菜单名称');
return false;
}
if ($('input[name="controller"]').val().trim() === '') {
error('请输入控制器');
return false;
}
//把form表单中的数据序列化后通过post提交
var form = $('form').serialize();
console.log(form);
$.post('/admins/menus/save',
form,
function(res) {
if (res.status > 0) {
error(res.msg);
} else {
layer.msg(res.msg);
setTimeout(function() {
//假设这是iframe页
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
//关闭当前窗口
parent.layer.close(index); //再执行关闭
//刷新父窗口,重新显示账号管理员列表
parent.window.location.reload();
}, 1000);
}
}, 'json');
function error(msg) {
layer.alert(msg, {
icon: 2
});
}
}
</script>
</html>
1.3修改菜单edit.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>添加菜单</title>
<style>
.layui-form {
margin-top: 20px;
margin-right: 20px;
}
</style>
</head>
<body>
<form action="" class="layui-form">
@csrf
<input type="hidden" name="mid" value="{{$menu['mid']}}">
<input type="hidden" name="pid" value="{{$menu['pid']}}">
<div class="layui-form-item">
<label for="" class="layui-form-label">菜单名称</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="title" value="{{$menu['title']}}">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">是否隐藏</label>
<div class="layui-input-inline">
<input type="checkbox" name="ishidden" lay-skin='switch' lay-text='正常|隐藏'
{{$menu['ishidden']?'':'checked'}}>
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">排序</label>
<div class="layui-input-inline">
<input type="number" class="layui-input" name="ord" value="{{$menu['ord']}}">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">controller</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="controller" value="{{$menu['controller']}}">
</div>
</div>
<div class="layui-form-item">
<label for="" class="layui-form-label">action</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="action" value="{{$menu['action']}}">
</div>
</div>
</form>
</body>
<script>
layui.use(['form', 'layer'], function() {
var form = layui.form;
var layer = layui.layer;
$ = layui.jquery;
});
//在父窗口中调用了save方法
function save() {
if ($('input[name="title"]').val().trim() === '') {
error('请输入菜单名称');
return false;
}
if ($('input[name="controller"]').val().trim() === '') {
error('请输入控制器');
return false;
}
//把form表单中的数据序列化后通过post提交
var form = $('form').serialize();
console.log(form);
$.post('/admins/menus/save',
form,
function(res) {
if (res.status > 0) {
error(res.msg);
} else {
layer.msg(res.msg);
setTimeout(function() {
//假设这是iframe页
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
//关闭当前窗口
parent.layer.close(index); //再执行关闭
//刷新父窗口,重新显示账号管理员列表
parent.window.location.reload();
}, 1000);
}
}, 'json');
function error(msg) {
layer.alert(msg, {
icon: 2
});
}
}
</script>
</html>
2.角色控制器Groups.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;//哈希密码加密
use Illuminate\Http\Request;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//后台角色管理控制器
class Groups extends Controller
{
public function index()
{
$res['groups'] = DB::table('admin_group')->lists();
return view('/admins/groups/index',$res);
}
public function add()
{
//查出所有可用的菜单
$menus = [];
$menus = DB::table('admin_menu')->where('status',0)->lists();
$res['pMenus'] = [];
foreach($menus as $menu):
if($menu['pid']=='0'):
$res['pMenus'][]=$menu;
$res['cMenus'][$menu['mid']]=[];
else:
$res['cMenus'][$menu['pid']][]=$menu;
endif;
endforeach;
// echo '<pre>';
// print_r($res);
// exit;
return view('/admins/groups/add',$res);
}
public function save(Request $req)
{
if(trim($req->title)==""):
return json_encode(['status'=>'1','msg'=>'必须输入角色名称']);
endif;
$data['title'] =trim($req->title) ;
if($req->menus):
$data['rights'] =json_encode(array_keys($req->menus));
else:
$data['rights']='';
endif;
$gid = (int)$req->gid;
if($gid):
$res = DB::table('admin_group')->where('gid',$gid)->update($data);
else:
$res = DB::table('admin_group')->insert($data);
endif;
if($res):
return json_encode(['status'=>'0','msg'=>'保存成功']);
else:
return json_encode(['status'=>'1','msg'=>'保存失败']);
endif;
exit;
}
public function edit(Request $req)
{
$gid = $req->gid;
$res['group'] = DB::table('admin_group')->where('gid',$gid)->item();
$menus = [];
$menus = DB::table('admin_menu')->where('status',0)->lists();
$res['pMenus'] = [];
foreach($menus as $menu):
if($menu['pid']=='0'):
$res['pMenus'][]=$menu;
$res['cMenus'][$menu['mid']]=[];
else:
$res['cMenus'][$menu['pid']][]=$menu;
endif;
endforeach;
$res['group']['rights']=json_decode($res['group']['rights'],true);
// echo '<pre>';
// print_r($res);
// exit;
return view('/admins/groups/edit',$res);
}
public function del(Request $req)
{
$gid = $req->gid;
$res =DB::table('admin_group')->where('gid',$gid)->delete();
if($res)
{
return json_encode(['status'=>'0','msg'=>'删除成功']);
}
else
{
return json_encode(['status'=>'1','msg'=>'删除失败']);
}
}
}
2.1角色列表index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>角色管理</title>
</head>
<style>
.addBtn {
margin-top: 10px;
width: 120px;
margin-left: auto;
margin-right: 50px;
}
.layui-table {
width: 95%;
margin: 20px;
}
</style>
<body>
<div class="addBtn">
<button class="layui-btn" onclick="add()">添加角色</button>
</div>
<table class="layui-table">
<thead>
<tr>
<th>编号</th>
<th>角色名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach($groups as $group)
<tr>
<td>{{$group['gid']}}</td>
<td>{{$group['title']}}</td>
<td>
<button class="layui-btn layui-btn-xs" onclick="edit({{$group['gid']}})">修改</button>
<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="del({{$group['gid']}})">删除</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
<script>
layui.use(['layer'], function() {
layer = layui.layer;
$ = layui.jquery;
});
//添加角色
function add() {
//iframe层
layer.open({
type: 2,
title: '添加角色',
shadeClose: true,
shade: 0.8,
area: ['380px', '80%'],
content: '/admins/groups/add', //iframe的url
btn: ['保存'],
yes: function(index, layero) {
//得到iframe页的窗口对象,执行iframe页的方法:iframeWin.子页面的方法名称();
var iframeWin = window[layero.find('iframe')[0]['name']];;
iframeWin.save();
}
});
}
//修改角色
function edit(id) {
//iframe层
layer.open({
type: 2,
title: '修改角色',
shadeClose: true,
shade: 0.8,
area: ['380px', '80%'],
content: '/admins/groups/edit?gid=' + id, //iframe的url
btn: ['保存'],
yes: function(index, layero) {
//得到iframe页的窗口对象,执行iframe页的方法:iframeWin.子页面的方法名称();
var iframeWin = window[layero.find('iframe')[0]['name']];;
iframeWin.save();
}
});
}
//删除角色
function del(id) {
layer.confirm('确认要删除角色吗?', function() {
$.get('/admins/groups/del?gid=' + id, function(res) {
if (res.status > 0) {
layer.alert(res.msg, {
icon: 2
});
} else {
layer.msg(res.msg, {
time: 3000
});
window.location.reload();
}
}, 'json');
});
}
</script>
</html>
2.2添加角色权限add.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>添加角色</title>
<style>
.layui-form {
margin-top: 20px;
margin-right: 20px;
}
</style>
</head>
<body>
<form action="" class="layui-form" lay-filter='groupForm'>
@csrf
<div class="layui-form-item">
<label for="" class="layui-form-label">角色名称</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="title">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 10px;">
<input type="checkbox" title="全选" lay-filter="checkAll">
</div>
</div>
@foreach($pMenus as $pMenu)
<hr>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 10px;">
<input type="checkbox" title="{{$pMenu['title']}}" value="{{$pMenu['mid']}}"
name="menus[{{$pMenu['mid']}}]" lay-filter="pmenus" group="{{$pMenu['mid']}}">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 50px;">
<?php $childs = $cMenus[$pMenu['mid']]?>
@foreach($childs as $child)
<input type="checkbox" lay-skin="primary" title="{{$child['title']}}" value="{{$child['mid']}}"
name="menus[{{$child['mid']}}]" lay-filter="cmenus-{{$child['pid']}}">
@endforeach()
</div>
</div>
@endforeach
</form>
</body>
<script>
layui.use(['form', 'layer'], function() {
var form = layui.form;
var layer = layui.layer;
$ = layui.jquery;
//全选按钮点击事件
form.on('checkbox(checkAll)', function(data) {
//data.elem.checked检查是否被选中
if (data.elem.checked) {
//全选按钮被选中
$('input[type="checkbox"]').attr('checked', 'true');
//渲染美化后的checkbox
$('input[type="checkbox"]~div').addClass('layui-form-checked');
} else {
$('input[type="checkbox"]').removeAttr('checked');
$('input[type="checkbox"]~div').removeClass('layui-form-checked');
//全选按钮未选中
}
// form.render('checkbox', 'groupForm');
});
//父级菜单选中事件
form.on('checkbox(pmenus)', function(data) {
//data.elem.checked检查是否被选中
var pIndex = $(data.elem).attr('group');
if (data.elem.checked) {
$('input[lay-filter="cmenus-' + pIndex + '"]').attr('checked', 'true');
//渲染美化后的checkbox
$('input[lay-filter="cmenus-' + pIndex + '"]~div').addClass('layui-form-checked');
} else {
$('input[lay-filter="cmenus-' + pIndex + '"]').removeAttr('checked');
$('input[lay-filter="cmenus-' + pIndex + '"]~div').removeClass('layui-form-checked');
}
// form.render('checkbox', 'groupForm');
});
});
//在父窗口中调用了save方法
function save() {
console.log('save');
if ($('input[name="title"]').val().trim() === '') {
error('请输入角色名称');
return false;
}
//把form表单中的数据序列化后通过post提交
var form = $('form').serialize();
$.post('/admins/groups/save',
form,
function(res) {
if (res.status > 0) {
error(res.msg);
} else {
layer.msg(res.msg);
setTimeout(function() {
//假设这是iframe页
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
//关闭当前窗口
parent.layer.close(index); //再执行关闭
//刷新父窗口,重新显示账号管理员列表
parent.window.location.reload();
}, 1000);
}
}, 'json');
}
function error(msg) {
layer.alert(msg, {
icon: 2
});
}
</script>
</html>
2.3修改角色权限edit.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
<script src="/static/plugins/layui/layui.js"></script>
<title>修改角色</title>
<style>
.layui-form {
margin-top: 20px;
margin-right: 20px;
}
</style>
</head>
<body>
<form action="" class="layui-form" lay-filter='groupForm'>
@csrf
<input type="hidden" name="gid" value="{{$group['gid']}}">
<div class="layui-form-item">
<label for="" class="layui-form-label">角色名称</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="title" value="{{$group['title']}}">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 10px;">
<input type="checkbox" title="全选" lay-filter="checkAll">
</div>
</div>
@foreach($pMenus as $pMenu)
<hr>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 10px;">
<input type="checkbox" title="{{$pMenu['title']}}" value="{{$pMenu['mid']}}"
name="menus[{{$pMenu['mid']}}]" {{in_array($pMenu['mid'],$group['rights'])?'checked':''}}>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-inline" style="margin-left: 50px;">
<?php $childs = $cMenus[$pMenu['mid']]?>
@foreach($childs as $child)
<input type="checkbox" lay-skin="primary" title="{{$child['title']}}" value="{{$child['mid']}}"
name="menus[{{$child['mid']}}]" {{in_array($child['mid'],$group['rights'])?'checked':''}}>
@endforeach()
</div>
</div>
@endforeach
</form>
</body>
<script>
layui.use(['form', 'layer'], function() {
var form = layui.form;
var layer = layui.layer;
$ = layui.jquery;
//全选按钮点击事件
form.on('checkbox(checkAll)', function(data) {
//data.elem.checked检查是否被选中
if (data.elem.checked) {
//全选按钮被选中
$('input[type="checkbox"]').attr('checked', 'true');
//渲染美化后的checkbox
$('input[type="checkbox"]~div').addClass('layui-form-checked');
} else {
$('input[type="checkbox"]').removeAttr('checked');
$('input[type="checkbox"]~div').removeClass('layui-form-checked');
//全选按钮未选中
}
// form.render('checkbox', 'groupForm');
});
//父级菜单选中事件
form.on('checkbox(pmenus)', function(data) {
//data.elem.checked检查是否被选中
var pIndex = $(data.elem).attr('group');
if (data.elem.checked) {
$('input[lay-filter="cmenus-' + pIndex + '"]').attr('checked', 'true');
//渲染美化后的checkbox
$('input[lay-filter="cmenus-' + pIndex + '"]~div').addClass('layui-form-checked');
} else {
$('input[lay-filter="cmenus-' + pIndex + '"]').removeAttr('checked');
$('input[lay-filter="cmenus-' + pIndex + '"]~div').removeClass('layui-form-checked');
}
// form.render('checkbox', 'groupForm');
});
});
//在父窗口中调用了save方法
function save() {
console.log('save');
if ($('input[name="title"]').val().trim() === '') {
error('请输入角色名称');
return false;
}
//把form表单中的数据序列化后通过post提交
var form = $('form').serialize();
$.post('/admins/groups/save',
form,
function(res) {
if (res.status > 0) {
error(res.msg);
} else {
layer.msg(res.msg);
setTimeout(function() {
//假设这是iframe页
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
//关闭当前窗口
parent.layer.close(index); //再执行关闭
//刷新父窗口,重新显示账号管理员列表
parent.window.location.reload();
}, 1000);
}
}, 'json');
}
function error(msg) {
layer.alert(msg, {
icon: 2
});
}
</script>
</html>
3.权限中间件RightsVerify.php
<?php
namespace App\Http\Middleware;
use Closure;
use Hamcrest\Arrays\IsArray;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//引入Auth类,获取当前登录的用户
use Illuminate\Support\Facades\Auth;
use function GuzzleHttp\json_decode;
class RightsVerify
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//获取当前登录用户的用户信息
$user = Auth::user();
//获取当前登录用户的角色id
$gid = $user->gid;
$gInfo = DB::table('admin_group')->where('gid',$gid)->item();
if(!$gInfo):
return response('不存在该角色',200);
endif;
//把所有当前用户可用的菜单保存在数组中
$rights = [];
if($gInfo['rights']):
$rights = json_decode($gInfo['rights'],true);
endif;
//检查当前用户访问的是哪个菜单,是否有权限访问,是否有该菜单
$curUrl = $request->route()->action['controller'];//返回当前访问的路由所对应的控制器和方法
//App\Http\Controllers\admins\Home@index
$pos = strrpos($curUrl,'\\');//从字符串右边开始查找\在字符串中的位置
$curUrl = substr($curUrl,$pos+1);
//Home@index
$pos = strpos($curUrl,'@');//获取分隔符的位置
$con = substr($curUrl,0,$pos);//获取要访问的控制器
$act = substr($curUrl,$pos+1);//获取要访问的方法
//在数据库中查找对应的菜单
$curMenu = DB::table('admin_menu')->where('controller',$con)->where('action',$act)->item();
if(!$curMenu):
return response('不存在此功能',200);
endif;
if($curMenu['status']==1):
return response('此功能已被禁用,请联系管理员开启此功能',200);
endif;
if(!(in_array($curMenu['mid'],$rights))):
return response('没有权限使用此菜单,请更改权限后使用',200);
endif;
// echo '<pre>';
// print_r($curMenu);
// exit;
//把登录用户的权限保存在request中的rights自定义属性中
$request->rights = $rights;
return $next($request);
}
}
4.Home控制器,根据用户权限查找对应菜单Home.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//后台主页
class Home extends Controller
{
public function index(Request $req)
{
//通过req中的自定义rights属性取得当前用户的权限菜单,rights属性在中间件RightsVerify.php中自定义
$rights = $req->rights;
//然后通过whereIn判断菜单是否在权限菜单中
$menus = DB::table('admin_menu')->whereIn('mid',$rights)->where('status',0)->lists();
$res = [];
foreach($menus as $menu ):
//ishidden为0代表该显示该菜单
//pid等于0的并且的为*菜单存储在pmenus中
if($menu['pid']=='0' && $menu['ishidden']=='0'):
$res['pmenus'][] = $menu;
//为每一个一级菜单创建一个数组用来存放二级菜单
$res['cmenus'][$menu['mid']] = [];
endif;
//pid不等于0的为子菜单,按照pid进行分组存储在cmenus中
if(($menu['pid']!='0')&&($menu['ishidden']=='0')):
//把子菜单放在对应的一级菜单的数据中
$res['cmenus'][$menu['pid']][] = $menu;
endif;
endforeach;
$res['username'] = Auth::user()->real_name;
// echo '<pre>';
// print_r($res);
// exit;
return view('/admins/home/index',$res);
}
public function welcome()
{
return view('/admins/home/welcome');
}
public function logout()
{
Auth::logout();
return view('/admins/account/login');
}
}
?>
上一篇: php笔记之:初探PHPcms模块开发介绍_PHP教程
下一篇: vue侦听器