Laravel使Acl用户具有权限(没有排名/组)

时间:2017-06-17 17:05:32

标签: php laravel permissions acl

我想创建可以授予权限的用户。 我创建了一个权限模型,其中包含以下属性(id | name | displayName | desc)

1|xyz.edit|Edit xyz| Allow to edit xyz
2|xyz.create|Create xyz| Allow to create xyz

因此,我想创建如下关系:

public function getPermissions(){
    return $this->hasMany('App\Permission');
}

但它不起作用。有没有办法创造像这样的关系 用户有很多权限,但没有为用户创建相同的权限? 我可以创建像id|pass|login|...|permissions这样的用户模型 并且在权限存储权限id中分配了","并在getPermissions()函数中创建如下内容:

public function getPerms(){
    foreach (explode($this->permssions,',')as $id ){
        //here load from database perm by id add to array and return
    }
}

或者,我在本教程https://www.youtube.com/watch?v=Kas2w2DBuFg中看到的第二个选项是创建另一个包含字段的user_perms

id|user_id|perms|id

但是最好的选择是什么?

1 个答案:

答案 0 :(得分:0)

您可以在两个模型中发布代码吗? (用户模型和权限模型?)没有看到,我无法看到您正在使用的关系类型,尽管看起来您使用的是一对多。

无论哪种方式......

您可以让用户为其分配权限,而无需担心群组是通过使用多对多关系。这需要3张桌子。用户表,权限表和数据透视表。

您可以在此处阅读有关多对多关系的信息:https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

但要给你一个纲要......

用户模型

public function permissions(){
    return $this->belongsToMany('App\Permission');
}

许可模式

public function users(){
    return $this->belongsToMany('App\User');
}

create_users_table迁移(字段名称并不重要,只要确保你有增量()一个)

$table->increments('id');
$table->string('name');
(etc, standard migration stuff)

create_permissions_table迁移(字段名称并不重要,只要确保你有增量()一个)

$table->increments('id');
$table->string('name');
$table->string('long_name');
(etc, standard migration stuff)

对于数据透视表,您需要按字母顺序使用两个表的单数名称(或者至少是默认值)

create_permission_user_table(这两个字段名称很重要,laravel期望这些名称,您不需要任何其他字段......如果您想要彻底,也可以设置外键关系)

$table->integer('permission_id');
$table->integer('user_id');

然后给用户一个权限,你就可以了

// Grab your user and permission, however you do that...
$permission = \App\Permission::first();
$user = \App\User::first();

// Then save the permission to the user (or the other way around, but it makes more sense this way)
$user->permissions()->save($permission);

这将让您拥有具有权限的用户:)

然后您可以使用$ user->权限访问一系列权限,并执行您需要进行的任何逻辑检查,以检查是否允许他们执行操作!

相关问题