I don't understand the logic... if the authenticated user has permission to edit-user or remove-user; then why do you need to also check if the subject User has any permissions of their own?
Duplicated queries
Hey guys 👋
I'm working on a couple of policy methods in Laravel, and I noticed that duplicate queries are being made. Here's an example of what I'm currently doing in UserPolicy.php:
public function edit(User $user, User $model): bool
{
if ($user->hasPermission('edit-user')) {
if ($model->permissions()->exists()) {
return false;
}
return true;
}
return false;
}
public function delete(User $user, User $model): bool
{
if ($user->hasPermission('remove-user')) {
if ($model->permissions()->exists()) {
return false;
}
return true;
}
return false;
}
@grayorc this is Eloquent Builder logic; there is no issue of eager-loading or not.
$model->permissions()->exists()
You can load a relationship count or an exists aggregate function on the Users query using the withCount or withExists methods:
User::query()
->withExists('permissions')
->get()
Then the logic in the Policy would look like this:
return $user->hasPermission('edit-user') && ! $model->permissions_exists;
But this might not work for all cases whenever you forget to load that exists property on a User instance (giving false negatives); an isAdmin implementation could handle possible permissions, permissions_exists or permissions_count properties, or fallback to the Eloquent Builder query when needed.
Please or to participate in this conversation.