4

everybody! I am using Laravel Spatie Permission Package. And I can get user's all assigned permissions like this.

$user->getAllPermissions()

However, I want to get all permissions with eager loading. Maybe like this.

$users = User::with('getAllPermissions')->get();

But this didn't worked.

I tried

$users = user::with('permissions')->get();

But query counts were same result with

$users = user::get();

So $user->getAllPermissions() is already eager loaded query?

Or is there any eager loaded query?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
LoveCoding
  • 1,121
  • 2
  • 12
  • 33

1 Answers1

12

It is a pretty tricky thing to do to get all permission with user lists.

$users = user::with('permissions')->get();

this will provide permissions model with users list. In this way, you will get only permissions assigned to a user. But the user has a role then role permission will not be added.

But $user->getAllPermissions(); function will give you all permission related to user role and permission. But we need all permission with the users' list.

I created a Mutators function to get permissions with the user list.

public function getPermissionAttribute()
{
    return $this->getAllPermissions();
}

now You can append in your model

protected $appends = [
    'permission'
]

Now to avoid recursive query (aka n+1 query problem, to avoid execute for each user one query), write your user query like this

$users = user::with(['permissions', 'roles'])->get();

Or Add in your user model

protected $with =[
   'permissions',
    'roles'
]

I think this will help you.

Francesco Taioli
  • 2,687
  • 1
  • 19
  • 34
Shahadat Hossain
  • 947
  • 9
  • 24