7 months ago

Applying authorization policies on model query...

Posted 7 months ago by neeonline


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()
    ->get() // Here is the place where only projects that the user can see will be returned...

Thank you!

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