Reputation: 1211
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?
Upvotes: 4
Views: 18998
Reputation: 979
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.
Upvotes: 12