【问题标题】:Laravel Making Acl Users with permissions(without ranks/groups)Laravel 使 Acl 用户具有权限(无等级/组)
【发布时间】:2017-11-20 07:00:35
【问题描述】:

我想创建可以授予权限的用户。 我创建了一个权限模型,其中包含以下属性 (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

但是什么是最好的选择呢?

【问题讨论】:

    标签: php laravel permissions acl


    【解决方案1】:

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

    不管怎样……

    让用户为他们分配权限而不用担心组的方法是使用多对多关系。这需要 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 迁移(字段名称并不重要,只要确保你有 increment() 之一)

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

    create_permissions_table 迁移(字段名称并不重要,只要确保您有 increment() 之一)

    $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->permissions 访问一组权限,并执行您需要的任何逻辑检查来检查他们是否被允许做事!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 2016-06-02
      • 2012-08-12
      • 2015-05-15
      • 2013-11-07
      • 2017-03-30
      • 1970-01-01
      • 2012-03-05
      相关资源
      最近更新 更多