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 everyObjects
of everyBranch
-
Admin
: will see everyObjects
of its ownBranch
and not from otherBranches
-
User
: will see everyObjects
he created an not any other in his ownBranch
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?