Skip to main content

HasMembers Trait

The HasMembers trait turns a model into a memberable context (tenant, organization, team, project) that can assign, query, and remove members.

When to Use

Use HasMembers when:

  • The model is the scope of membership (not the person)
  • You want $tenant->assignMember($user, $role) instead of building morph arrays manually
  • You need to list active members of a context

Pair with HasRole on the personable side and register the model in RoleTypeRegistry.

Namespace

JobMetric\Rolix\Traits\HasMembers

Basic Usage

use Illuminate\Database\Eloquent\Model;
use JobMetric\Rolix\Traits\HasMembers;

class Tenant extends Model
{
use HasMembers;
}
use JobMetric\Rolix\Facades\RoleTypeRegistry;

RoleTypeRegistry::register('tenant', [
'model' => Tenant::class,
'hierarchical' => true,
]);

Methods

memberships()

public function memberships(): MorphMany

Morph-many relation as memberable.


members()

Active (non-expired) memberships for this memberable.

public function members(?string $collection = null): Collection
ParameterTypeDescription
$collectionstring|nullOptional collection filter

Returns: Collection of Membership models

$all = $tenant->members();
$ops = $tenant->members('ops');

assignMember()

Assign a personable to this memberable with a role (via Membership service).

public function assignMember(
Model $personable,
Role|int $role,
array $attributes = []
): Membership
ParameterDescription
$personableUser (or any HasRole model)
$roleRole model or id
$attributesExtra fields: collection, is_owner, allow, deny, expired_at, …

Returns: created Membership

$membership = $tenant->assignMember($user, $role, [
'collection' => 'ops',
'is_owner' => false,
]);

removeMember()

Soft-delete memberships for a personable on this memberable.

public function removeMember(
Model $personable,
Role|int|null $role = null,
?string $collection = null
): int

When $role is null, all roles for that personable on this memberable are removed (optionally filtered by collection).

Returns: number of destroyed memberships

$tenant->removeMember($user, $role);
$tenant->removeMember($user); // all roles on this tenant

hasMember()

Whether a personable has an active membership on this memberable.

public function hasMember(
Model $personable,
Role|int|null $role = null,
?string $collection = null
): bool
if ($tenant->hasMember($user, $role)) {
// ...
}

Example: Invite Flow

$role = Role::store([
'type' => 'tenant',
'name' => 'Member',
'allow' => ['workspace.view'],
])->data;

$tenant->assignMember($user, $role->id);

assert($tenant->hasMember($user, $role->id));
assert($user->hasPermission('workspace.view', $tenant));