Skip to content

Instantly share code, notes, and snippets.

@lucacastelnuovo
Created July 28, 2023 21:38
Show Gist options
  • Save lucacastelnuovo/c25416192a554b5b923d305856c35e38 to your computer and use it in GitHub Desktop.
Save lucacastelnuovo/c25416192a554b5b923d305856c35e38 to your computer and use it in GitHub Desktop.
Filament V3 multi-tenancy & laravel-permission role helper
<?php
namespace App\Models\Support;
use App\Models\Tenant;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Permission\Traits\HasRoles as SpatieHasRoles;
trait HasRoles
{
use SpatieHasRoles;
public function rolesOnTenant(Tenant $tenant): BelongsToMany
{
$originalTenantId = getPermissionsTeamId();
setPermissionsTeamId($tenant);
$roles = $this->roles();
setPermissionsTeamId($originalTenantId);
return $roles;
}
public function syncRolesOnTenant(
Tenant $tenant,
array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection|string|int $roles
): self {
$originalTenantId = getPermissionsTeamId();
setPermissionsTeamId($tenant);
$this->syncRoles($roles);
setPermissionsTeamId($originalTenantId);
return $this;
}
public function assignRoleOnTenant(
Tenant $tenant,
array|string|int|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $role
): self {
$originalTenantId = getPermissionsTeamId();
setPermissionsTeamId($tenant);
$this->assignRole($role);
setPermissionsTeamId($originalTenantId);
return $this;
}
}
@bilogic
Copy link

bilogic commented Dec 11, 2024

hi

  1. Is this like a drop in replacement?
  2. Does setPermissionsTeamId accept any model as long as it represents a tenant?
  3. Who will call and check with rolesOnTenant?

thanks!

@lucacastelnuovo
Copy link
Author

Hi @bilogic,

  1. This is not so much a replacement, it is more some extended functionality of spatie/laravel-permissions.
  2. To see how setPermisisonsTeamId works, have a look at this: https://spatie.be/docs/laravel-permission/v6/basic-usage/teams-permissions
  3. I do not understand this question, any part of your code can call this method.

@bilogic
Copy link

bilogic commented Dec 12, 2024

ok thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment