2019-02-15 12:15
浏览 182

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

So this is my current setup:


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


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


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


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

    解决 无用
    打赏 举报

相关推荐 更多相似问题