How can I group permissions, show them to the user and save without exceptions?

What I am trying to do: I'm using the role/permissions package from Spatie. Each permission has a group and can belong to a role. I'm trying to display the permissions on the Create + Edit Role page. What I did: I tried different layouts and tried to set different relationships. My issue/the error: When I save the permissions I get the exception: Add [permissions] to fillable property to allow mass assignment on [Spatie\Permission\Models\Role]. Code:
Grid::make()
->schema(
fn () => Permission::all()->pluck('group')->unique()->map(
fn ($group) =>
Section::make()
->label(__('permissions.group.' . $group))
->schema([
CheckboxList::make('permissions.' . $group)
->bulkToggleable()
->hiddenLabel()
->relationship(
'permissions',
'name',
modifyQueryUsing: fn ($query) => $query->where('group', $group)
)
->getOptionLabelFromRecordUsing(
fn (Permission $record) => __('permissions.'. $record->name)
)
->columnSpanFull()
])
)->toArray()
)
->columnSpanFull()
->columns([
'sm' => 1,
'md' => 2,
'lg' => 2,
'xl' => 3,
'2xl' => 4,
])
Grid::make()
->schema(
fn () => Permission::all()->pluck('group')->unique()->map(
fn ($group) =>
Section::make()
->label(__('permissions.group.' . $group))
->schema([
CheckboxList::make('permissions.' . $group)
->bulkToggleable()
->hiddenLabel()
->relationship(
'permissions',
'name',
modifyQueryUsing: fn ($query) => $query->where('group', $group)
)
->getOptionLabelFromRecordUsing(
fn (Permission $record) => __('permissions.'. $record->name)
)
->columnSpanFull()
])
)->toArray()
)
->columnSpanFull()
->columns([
'sm' => 1,
'md' => 2,
'lg' => 2,
'xl' => 3,
'2xl' => 4,
])
Solution:
On our EditRole we do the attached.
Jump to solution
6 Replies
toeknee
toeknee5w ago
It's because you are not attaching the permissions to the record you are trying to save them on the role by the looks of it. Spatie have great doc's on how to assign permissions. I assume you are assigning them directly? to a roll as a checkbox. You need to mutate the date and don't save the 'permissions' to the role model. Let me see how we do it
TDDeveloper
TDDeveloperOP5w ago
Initially I was wondering if this is the best way to display the permissions per group
Solution
toeknee
toeknee5w ago
On our EditRole we do the attached.
toeknee
toeknee5w ago
And on our RoleManagerResource we do:
toeknee
toeknee5w ago
So this displays them in groups It is based on the #althinect-spatie-roles-permissions plugin
TDDeveloper
TDDeveloperOP5w ago
Ah bad debugging on my part, this fixes my problem:
protected function mutateFormDataBeforeSave(array $data): array
{
unset($data['permissions']);
}
protected function mutateFormDataBeforeSave(array $data): array
{
unset($data['permissions']);
}

Did you find this page helpful?