Synchronizing Permissions with Spatie Permissions

Asked

Viewed 277 times

0

I need a little help, I need to synchronize permissions when creating and editing a user within the Administrator.

I’m using the Laravel Spartie Permission package, which I need to synchronize roles to the model_has_role and I’m not able to abstract the code to implement.

On the table roles I have all permissions, the problem as I said was to sync it at the time I register or edit the user.

    /**
     * @param Request $request
     * @param EloquentModel|Model $model
     */
    protected function syncPermissions(Request $request, Model $model)
    {
        $model->brands()->sync($request->input('brands'));
        $model->dealerships()->sync($request->input('dealerships'));

        $roles  = [];
        $permissions = [];


        dd($request->input('permissions'));

        $model->syncPermissions($permissions);
        $model->syncRoles($roles);
    }

Result of dd($request->input('permissions'));

array:3 [▼
  "admin" => array:1 [▼
    0 => "admin"
  ]
  "brands" => array:1 [▼
    "haojue" => "admin"
  ]
  "dealerships" => array:1 [▼
    "fortaleza" => "admin"
  ]
]

1 answer

0

protected function syncPermissions(Request $request, Model $model)
{
    $model->brands()->sync($request->input('brands'));
    $model->dealerships()->sync($request->input('dealerships'));

    $roles = [];
    $permissions = $request['permissions'];

    foreach ($permissions as $context => $permission) {
        // Verificando o primeiro nivel de permissão do novo usuário
        if ($context === 'admin') {
            foreach ($permission as $value) {
                $roles[] = $context . '.' . $value;
            }
        } else {
            // Verificando as permissões que o user tem em Brands e Dealeships
            foreach ($permission as $key => $value) {
                $roles[] = str_singular($context) . ':' . $key . ':' . $value;
            }
        }
    }
    $model->syncRoles($roles);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.