FilamentF
Filament16mo ago
jamesro

Add roles / permissions per team for user

Hello,

I have a case where I use spatie permissions, and I want to be able to give user roles and permissions on a team, can someone help with with the set of relations I have to do?

I have:

User - model

php public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class, 'team_user')->using(TeamUser::class);
    }


Team - Model

public function users()
    {
        return $this->hasMany(TeamUser::class);
    }



TeamUser - Model

public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function team()
    {
        return $this->belongsTo(Team::class, 'team_id');
    }



public function roles(): BelongsToMany
    {
        $relation = $this->morphToMany(
            config('permission.models.role'),
            'model',
            config('permission.table_names.model_has_roles'),
            config('permission.column_names.model_morph_key'),
            app(PermissionRegistrar::class)->pivotRole
        );


        if (! app(PermissionRegistrar::class)->teams) {
            return $relation;
        }

        $teamsKey = app(PermissionRegistrar::class)->teamsKey;
        $relation->withPivot($teamsKey);
        $teamField = config('permission.table_names.roles').'.'.$teamsKey;


        return $relation->wherePivot($teamsKey, $this->team_id);
            //->where(fn ($q) => $q->whereNull($teamField)->orWhere($teamField, $this->team_id));
    }


But I get an error when I try to save the team, when I select user roles




This is how I was thinking to make it using repeater,

Any help would be really appriciated.

Thanks
Screenshot_2024-09-25_at_11.26.02_PM.png
Was this page helpful?