Laravel Global Scope in Queue Jobs: Why It Should Fail Closed
A Laravel global scope can quietly leak data inside a queue job. I found this bug in a multi-branch app I built. Nothing crashed. No error showed up. The report just ran with the wrong data.
In this post, I explain what went wrong and how to fix it.
The Setup: A Branch Scope
My app has many branches. Each user belongs to one branch. A global scope keeps every query limited to the user's branch.
Here is the first version:
class BranchScope implements Scope { public function apply ( Builder $builder , Model $model ): void { $branchId = auth () -> user () ?-> branch_id ;
if ( $branchId === null ) { return ; // no branch, so no filter }
$builder -> where ( 'branch_id' , $branchId ); } }
Enter fullscreen mode
Exit fullscreen mode
In a web request, this works well. The user is logged in. The scope knows the branch.
The Bug: Queue Jobs Have No Logged-In User
A queue job runs in the background. No one is logged in.…