创建角色表
先创建迁移
php artisan make:migration create_roles_table
编写迁移文件
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name','20')->comment('角色名称');
$table->timestamps();
// 软删除
$table->softDeletes();
});
创建节点表
php artisan make:migration create_nodes_table
编写节点迁移数据
Schema::create('nodes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name',50)->comment('节点名称');
$table->string('route_name',100)->nullable()->default('')->comment('路由别名,权限认证标识');
$table->unsignedInteger('pid')->default(0)->comment('上级ID');
$table->enum('is_menu',['0','1'])->default('0')->comment('是否为菜单0否,1是');
$table->timestamps();
$table->softDeletes();
});
创建中间表,用来链接两个表的内容
php artisan make:migration create_role_node_table
编写迁移数据
Schema::create('role_node', function (Blueprint $table) {
// 角色ID
$table->unsignedInteger('role_id')->default(0)->comment('角色ID');
// 节点ID
$table->unsignedInteger('node_id')->default(0)->comment('节点ID');
});
之后执行迁移
php artisan migrate
创建模型层
角色模型
php artisan make:model Models/Role
需要继承管理模型
class Role extends Base
{
// 角色与权限 多对多
public function nodes() {
// 参1 关联模型
// 参2 中间表的表名,没有前缀
// 参3 本模型对应的外键ID
// 参4 关联模型对应的外键ID
return $this->belongsToMany(Node::class,'role_node','role_id','node_id');
}
}
编写节点模型
php artisan make:model Models/Node
编写setRouteNameAttribute方法
// 修改器 route_name RouteName set字段名Attribute 字段名首字母大写,遇下划线后字母大写
public function setRouteNameAttribute($value) {
// 如果字段值为null,则设置为空字符串 修改和添加时生效 create 或 update
$this->attributes['route_name'] = empty($value) ? '' : $value;
}
编写菜单访问器方法
public function getMenuAttribute() {
return $this->is_menu == '1' ? '<span class="label label-success radius">是</span>' : '<span class="label label-danger radius">否</span>';
}
获取全部数据
// 获取全部的数据
public function getAllList() {
$data = self::get()->toArray();
return $this->treeLevel($data);
}
获得层级目录
public function treeData($allow_node) {
$query = Node::where('is_menu', '1');
if (is_array($allow_node)) {
$query->whereIn('id', array_keys($allow_node));
}
$menuData = $query->get()->toArray();
return $this->subTree($menuData);
}
编写控制器
创建角色控制器
php artisan make:controller Admin/RoleController
展示角色列表
public function index(Request $r