Home > Enterprise >  How can I get permissions id of subrequest?
How can I get permissions id of subrequest?

Time:02-22

With spatie/laravel-permission I try to get Role and joined permissions id, something like :

$role = Role
    ::getById($role_id)
    ->with('permissions')->pluck('id')
    ->first();

        

I do not get any error but $role is invalid.

Can I do it, if yes in which way ?

Thanks!

CodePudding user response:

App\Models\Role::where('id', $roleId)->with('permissions')->first()->permissions->pluck('id')->toArray();

Here you can chain all permissionIds from Role or you can use:

App\Models\Role::where('id', $roleId)->first()->permissions->pluck('id')->toArray();

CodePudding user response:

To get the Role and the permissions associated to it

$role = App\Models\Role::where('id', $roleId)->with('permissions')->first();
$permissions = $role->permissions;

//if you only need the permissions without first getting the role (just with the role id)
$permissions = App\Models\Permission::whereHas('roles', function($roleQuery) use ($roleId) {
    $roleQuery->where('id', $roleId);
})->get();

//if you just need the list of ids of the role permissions
$permissionIds = App\Models\Permission::whereHas('roles', function($roleQuery) use ($roleId) {
    $roleQuery->where('id', $roleId);
})->pluck('id')->toArray();

//if you already have a $role instance (not just its ID)
$permissionIds = $role->permissions()->pluck('id')->toArray();

//if you only need the first permission id of a role switch pluck('id')->toArray() with ->value('id')
$firstPermissionId = $role->permissions()->value('id');
//or
$firstPermissionId = App\Models\Permission::whereHas('roles', function($roleQuery) use ($roleId) {
    $roleQuery->where('id', $roleId);
})->value('id');
  • Related