bouncer icon indicating copy to clipboard operation
bouncer copied to clipboard

[Help] Efficient way to query roles against multiple scopes?

Open hailwood opened this issue 6 years ago • 1 comments

So in my case a tenant is an "Organisation".

We can get a list of the organisations via $user->organisations / $user->organisations()->get().

And assuming we've used $bouncer->scope()->to(1) then a call to $user->getRoles() will return the users roles against Organisation 1, easy.

But now before we apply a scope we want to display the list of organisations, and the users roles against the given organisations.

The best I've found is adding a method onto User

public function rolesByScope($scope)
{
  $bouncer = resolve(Bouncer::class);
  return $bouncer->scope()->onceTo($scope, function () {
    return $this->getRoles();
  });
}

Which works

foreach($user->organisations as $organisation) {
    echo "<br />{$organisation->name}: " . $user->rolesByScope($organisation->id)->implode(', ');
}

But I'm wondering if there's a more direct way of loading the roles, perhaps adding a new relationship to the Organisation Model so I can eager load them?

hailwood avatar May 01 '19 04:05 hailwood

It'd be nice if $this->getRoles(); returned the Role models. Or, a variant, such as $this->getRoles('title'); so it returns a different table field, because name is not always what we want -- eg. may want the human readable titles.

cjaoude avatar Dec 28 '21 14:12 cjaoude