How to safely scope queries by user permissions?

3 days ago 9
ARTICLE AD BOX

I have a multi-tenant Laravel app using a shared database with tenant scoping. Each organization can define base permissions for its members. Example: if resource.view is enabled, all members can view all resources by default; if it is disabled, only users explicitly assigned to a resource can view it.

Right now I filter projects like this:

$projects = Projects::query() // scoped ->all() ->filter(fn (Project $project) => $user->can('view', $project));

The problem is that a single mistake (like simply forgetting to apply filter) can leak data between members. I tried creating a global scope similar to my tenant scope, but it quickly becomes complicated. I also can't simply do Gate::authorize('viewAny', Project::class);

What is the recommended way to enforce per-resource authorization at the query level so I don't risk leaking data?

Read Entire Article