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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。