'How can I get permissions id of subrequest?

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!



Solution 1:[1]

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();

Solution 2:[2]

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) with only one query
$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 with only one query
$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 with only one query
$firstPermissionId = App\Models\Permission::whereHas('roles', function($roleQuery) use ($roleId) {
    $roleQuery->where('id', $roleId);
})->value('id');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gguney
Solution 2