Applying authorization policies on model query...

Posted 4 months ago by neeonline

Hello,

Let's say my App has this models: User, Team, Projects... Using authorization gates I can define if the logged user can view/control a project. No problem there.

// User can't see all projects in his team...
public function view(User $user, Project $project)
{
    return $user->teams->contains($project->team) && $user->anotherRuleFor($project) && ...;
}

public function control(User $user, Project $project)
{
    return $user->hasPermission('project-edit') && $this->view($user, $project);
}

Now, my question is:

Is it possible to apply the view check while loading the projects for the user?

Something like:

$projectsThatUserCanView = $user->teams()
    ->with('projects')
    ->get() // Here is the place where only projects that the user can see will be returned...
    ->pluck('projects')
    ->toArray();

Thank you!

Please sign in or create an account to participate in this conversation.