Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajgagnon's avatar

Duplicate User Query in Policy

I have a policy that seems to be duplicating the authorized user query. I'm seeing this query:

select * from `users` where `id` = 1 limit 1

/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php:52

And also this one, which is slightly different in my policy:

select * from `users` where `users`.`id` = 1 limit 1

/app/Policies/ProjectPolicy.php:20

Here's what the ProjectPolicy method looks like:

public function view(User $user, Project $project)
    {
        return $user->is($project->owner);
    }

And in the user model:

 /**
     * A user has their own projects
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function projects()
    {
        return $this->hasMany(Project::class, 'owner_id');
    }

Anyone experienced this issue before?

0 likes
4 replies
Mahin's avatar

which version of laravel? and how do you verifying that these queries are duplicate?

Mahin's avatar
Mahin
Best Answer
Level 28

@ajgagnon those two users are queried by completely two different modules. First one was queried by Auth Service Provider and the second one was queried in the policy when you are using $project->owner (this is an eloquent relationship which isn't eager loaded)

One alternative to this to avoid the last query is:

public function view(User $user, Project $project)
{
        return $user->id == $project->owner_id;
}

Please or to participate in this conversation.