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

pickab00's avatar

Query Scope with Spatie Permission

Hello,

I am writing a query scope based on the Permissions the user has using Spatie Permission Package. And this is what I have so far.

$query->when($readAllRequests, function ($request) use ($admin) {
    // do nothing when they can read all requests
});
$query->when($readAssignedRequests, function ($request) use ($admin) {
    $request->where('receiver_id', $admin->id);
});
$query->when($readDepartmentRequests, function ($request) use ($admin) {
    $request->where('department_id', $admin->department_id);
});

When the user has $readAllRequests, then they should be able to see all the requests. When the user has $readAssignedRequests, then they can only read the requests received to them. Right now if I remove the users permission to read all requests, they can read their own requests which is fine. But if I give them the permission to read all requests, it would still look for the receiver_id and department_id. How can I say that I am looking for both receiver_id, department_id and all requests depending on the permission?

0 likes
1 reply
pickab00's avatar
pickab00
OP
Best Answer
Level 4

The answer was so simple.

Use:

$query->where(function ($query) {
	$query->when($readAssignedRequests, function ($request) use ($admin) {
        $request->where('receiver_id', $admin->id);
    })->when($readDepartmentRequests, function ($request) use ($admin) {
        $request->where('department_id', $admin->department_id);
    });
})

https://laravel.com/docs/8.x/queries#logical-grouping

Please or to participate in this conversation.