I have 3 models for managing user permissions.
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function permissions()
{
return $this->belongsToMany('App\Models\Permission');
}
}
class Permission extends Model
{
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
public function roleHavePermission(Role $role)
{
if ($this->roles()->find($role->id)) {
return true;
}
return false;
}
public function userHavePermission(User $user = null)
{
$roles = [];
if (is_null($user)) {
$roles[] = Role::where('slug', 'guest')->first();
} else {
foreach ($user->roles as $role) {
$roles[] = $role;
}
}
foreach ($roles as $role) {
if ($this->roleHavePermission($role)) {
return true;
}
}
return false;
}
}
Now because my application is grown, I'm moving to repositories. For example this is my PermissionRepository:
class PermissionRepository implements PermissionRepositoryInterface
{
protected $roleRepository;
/**
* PermissionRepository constructor.
* @param RoleRepositoryInterface $roleRepository
*/
public function __construct(RoleRepositoryInterface $roleRepository)
{
$this->roleRepository = $roleRepository;
}
public function action($routeName)
{
return Permission::where('action', $routeName)->first();
}
}
How can I implement roleHavePermission and userHavePermission in this repository? I tried implementing roles method with this syntax:
public function roles()
{
return Permission::roles();
}
But it wont work since Permission's roles method can not called statically. Thanks.