[英]Laravel Spatie/Permission filter for multi-tenant
I have 3 main models: 我有3个主要模型:
Every user will belong to a Branch
and a Branch
will have many Users
. 每个用户将属于一个
Branch
而一个Branch
将有许多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
将属于Users
并且也属于Branch
,因此Objects
具有user_id
和branch_id
如下所示:
//Objects DB table tructure
[
"id",
"name",
"branch_id",
"user_id",
"created_at",
"updated_at",
]
So this is my current setup: 这是我当前的设置:
Models/Branch.php 型号/ Branch.php
public function users()
{
return $this->hasMany(User::class);
}
Models/Users.php 型号/ Users.php
public function branch()
{
return $this->belongsTo(Branch::class);
}
Models/Objects.php 型号/ Objects.php
public function user()
{
return $this->belongsTo(User::class);
}
Now I've setup Spatie/Permission with following Roles
: 现在,我已设置具有以下
Roles
Spatie / Permission :
Super-Admin
: will see every Objects
of every Branch
Super-Admin
:将看到每个Branch
每个Objects
Admin
: will see every Objects
of its own Branch
and not from other Branches
Admin
:将看到自己Branch
每个Objects
,而不是其他Branches
User
: will see every Objects
he created an not any other in his own Branch
or outside of it User
:将看到他创建的每个Objects
在其自己的Branch
或Branch
之外的其他Objects
My point now is to list all Objects
based off of the User permission. 我现在的观点是根据“用户”权限列出所有
Objects
。 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?
我是否应该使用其他更合适的Laravel功能/ API?
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 您正在检索给定时间的用户对象的对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.