首先,权限系统参考
http://9iphp.com/web/laravel/laravel-5-acl-define.html
该文章编写的。
Model:
CommonUser.php
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CommonUser extends Authenticatable
{
public function groups()
{
return $this->belongsToMany(CommonGroup::class, 'common_group_user', 'user_id', 'group_id');
}
// 判断用户是否属于某个用户组
public function hasGroup($group)
{
if (is_string($group)) {
return $this->groups->contains('name', $group);
}
return !! $group->intersect($this->groups)->count();
}
// 判断用户是否具有某权限
public function hasPermission($permission)
{
return $this->hasGroup($permission->groups);
}
// 给用户分配角色
public function assignGroup($group)
{
return $this->groups()->save(
CommonGroup::whereName($group)->firstOrFail()
);
}
}
CommonGroup.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CommonGroup extends Model
{
protected $table = 'common_groups';
protected $fillable = [
'name', 'label', 'description',
];
public function permissions()
{
return $this->belongsToMany(CommonPermission::class, 'common_permission_group', 'group_id', 'permission_id');
}
//给用户组添加权限
public function givePermissionTo($permission)
{
return $this->permissions()->save($permission);
}
}
CommonPermission.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CommonPermission extends Model
{
protected $table = 'common_permissions';
protected $fillable = [
'name', 'label', 'description',
];
public function groups()
{
return $this->belongsToMany(CommonGroup::class, 'common_permission_group', 'permission_id', 'group_id');
}
}
App\Providers\AuthServiceProvider.php
public function boot(GateContract $gate)
{
// $this->registerPolicies($gate);
parent::registerPolicies($gate);
$permissions = \App\Models\CommonPermission::with('groups')->get();
foreach ($permissions as $permission) {
$gate->define($permission->name, function($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
Database
1. common_users
id: 1
username: Bantes
2. common_groups
id: 1
name: admin
3. common_permissions
id: 1
name: show-system-setting
4. common_group_user
user_id: 1
group_id: 1
5. common_permission_group
group_id: 1
`
Blade
layout.blade.php
|@include(menu.blade.php)
index.blade.php
|@extends(layout.blade.php)