I have 3 main models:
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.