doumi1944 2019-02-15 12:15
浏览 194
已采纳

Laravel Spatie /多租户权限过滤器

I have 3 main models:

  • Users
  • Branches
  • Objects

Every user will belong to a Branch and a Branch will have many Users.

Objects will belong to Users and to Branch as well, so Objects has a user_id as well as a branch_id like so:

//Objects DB table tructure
[
 "id",
 "name",
 "branch_id",
 "user_id",
 "created_at",
 "updated_at",
]

So this is my current setup:

Models/Branch.php

public function users()
{
    return $this->hasMany(User::class);
}

Models/Users.php

public function branch()
{
    return $this->belongsTo(Branch::class);
}

Models/Objects.php

public function user()
{
    return $this->belongsTo(User::class);
}

Now I've setup Spatie/Permission with following Roles:

  • Super-Admin: will see every Objects of every Branch
  • Admin: will see every Objects of its own Branch and not from other Branches
  • User: will see every Objects he created an not any other in his own Branch or outside of it

My point now is to list all Objects based off of the User permission. My first idea is to build relations based on models, but I'm not sure this is a good idea and practice, this is the code:

public function objects(){

    $user = auth()->user();

    if ($user->hasRole("Super-Admin")) {
        return Object::query();
    }

    if ($user->hasRole("Admin")) {
        return Object::where('branch_id', '=', $user->branch()->pluck('id'));
    }

    return $this->hasMany(Object::class);

}

Does this make sense at all? Should I use any other more appropriate Laravel functionalities/API?

  • 写回答

1条回答 默认 最新

  • duanhua5523 2019-02-15 13:41
    关注

    The aproach you are using does make sense, the only thing that concerns me is using the authenticated user inside a function on the model.

    That could cause same conflicts, for example if a super-admin wants to see the objects of a normal user then this function is no good for you because all the time you are going to retrieve the objects of the super-admin.

    i would use your function as follows

    public function objects(){
    
       if ($this->hasRole("Super-Admin")) {
           return Object::query();
       }
    
       if ($this->hasRole("Admin")) {
           return Object::where('branch_id', '=', $this->branch()->pluck('id'));
       }
    
       return $this->hasMany(Object::class);
    }
    

    And then on the Controllers when using

    $user->objects();
    

    you are retrieving the objects of the user object you have at the given time

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?