serenysoft / nova-permissions

Laravel Nova 4 Roles & Permissions
72 stars 25 forks source link

A method to add Select field to chose the role on create / update #28

Closed beshoo closed 1 year ago

beshoo commented 1 year ago

As we know, we can not attach roles upon creation or updating. https://github.com/serenysoft/nova-permissions/issues/21

You need to go to attach method on the module page!

image

Well, I created a simple select while retrieving all available roles and only isSuperAdmin can see it.

 Select::make('Role')
                ->options(function () {
                    return \Spatie\Permission\Models\Role::pluck('name')->mapWithKeys(function ($value) {
                        return [$value => $value];
                    });
                })
                ->fillUsing(function () {
                    return null;
                })->hideFromIndex()->hideFromDetail()->resolveUsing(function ($request, $model) {
                    return $model->getRoleNames();
                })->rules('required')->canSee(function ($request) {
                   return ($request->user()->isSuperAdmin());
                }
                )

To update the role we need to syncRoles! this will remove any previous role/permissions and here is the afterCreate/afterUpdate

public static function afterCreate(NovaRequest $request, Model $model)
    {
         $model->syncRoles([$request->role]);
    }

    public static function afterUpdate(NovaRequest $request, Model $model)
    {
         $model->syncRoles([$request->role]);
    }

Now once you want to create/update a record you can attach the role directly

image

beshoo commented 1 year ago

On the other hand, you can use https://github.com/blendbyte/nova-attach-many

leandrogehlen commented 1 year ago

This is a request?

If yes, it is not the pupouse of repository

beshoo commented 1 year ago

I'm actually helping another user to find a way to add this functionality to another resource.

leandrogehlen commented 1 year ago

I don't undersand. Is not more easy add a HasMany relation to resource?

beshoo commented 1 year ago

I'm not sure if I understand correctly, but using HasMany::make('Roles') won't provide a select option to choose from when creating or updating a user.

leandrogehlen commented 1 year ago

No, but allows the user add multiple roles to resource as the same way.

If you want something more flexible you can you use:

https://nova.laravel.com/docs/4.0/resources/repeater-fields.html

beshoo commented 1 year ago

My method is easier and will syncRoles the role on create and update..

image

leandrogehlen commented 1 year ago

If you want that a resource has just one role you should delcare a belongsTo relation in your model and use BelongsTo in resource