您需要如下设置。创建具有四个表(users、roles、permissions 和permission_role)的类(模型):
Table roles
:
id | name (role name)
1 | admin
2 | user
Model Role
:
class Role extends ELoquent {
protected $table = 'roles';
public function users()
{
return $this->hasMany('User', 'role_id', 'id');
}
public function permissions()
{
return $this->belongsToMany('Permission');
}
}
Table permissions
:
id | name (permission name)
1 | manage_pages (add/edit/delete)
2 | manage_users (add/edit/delete)
3 | page_about (access allowed to about page)
4 | page_contact (access allowed to contact page)
Model Permission
class Permission extends ELoquent {
protected $table = 'permissions';
public function roles()
{
return $this->belongsToMany('Role');
}
}
Table users
:
id | username | email | password | role_id | more...
1 | admin | [email protected] /cdn-cgi/l/email-protection | hashed | 1 | more...
2 | user1 | [email protected] /cdn-cgi/l/email-protection | hashed | 2 | more...
3 | user2 | [email protected] /cdn-cgi/l/email-protection | hashed | 2 | more...
Model User
class User extends ELoquent {
protected $table = 'users';
public function role()
{
return $this->belongsTo('Role', 'role_id', 'id');
}
public function can($perm = null)
{
if(is_null($perm)) return false;
$perms = $this->role->permissions->fetch('name');
return in_array($perm, $perms->toArray());
}
}
Table permission_role
(数据透视表):
id | permission_id | role_id
1 | 1 | 1
2 | 2 | 1
3 | 3 | 1
4 | 4 | 1
5 | 3 | 2
6 | 4 | 2
一旦完成此设置,您就可以创建过滤器,或者在类方法中您可以检查登录用户是否具有特定规则或权限,然后允许访问页面,否则不允许。例如,您可以使用如下方式检查登录用户是否可以访问页面:
if(Auth::user->can('manage_pages')) {
// Let him/her to add/edit/delete any page
}
由于您的页面是动态的并且所有页面都由show
方法然后在你的show
方法你可以检查这样的东西:
public function show($slug = 'home')
{
// assumed page slug is 'about'
$permission = 'page_' . $slug;
if(Auth::user->can($permission)) {
$page = page::whereSlug('home')->get();
return View::make('pages.index')->with('page', $page);
}
}
这确实是一个很大的问题,需要你自己去解决。我向您提供了一些实现的基本想法,现在您应该扩展它。
P/S:不可能从地面回答所有问题,但我参与了您的同一个项目的另一个答案,我建议您实施权限基础(ACL),所以我试图提供帮助,但您需要尝试执行其余部分。一切顺利。