I am working on an app, in which each user is assigned a particular region. For example, user 1 belongs to a region 'Phoenix', user 2 to 'Scottsdale', and user 3 to 'Tempe'. The region of each user is defined in the region_id column.
The app has 3 separate guards for 3 different user models (it's a marketplace with regional managers, providers, and customers). Virtually every model in the app has a region_id column, identifying to which region the resource belongs to.
I would like to simplify how the resources are queried. Currently, I am filtering each model/resource directly in the controller, e.g.:
$customers = Customer::where('region_id', Auth::user()->region_id);
I would like to set such filters at the global level, to make sure that each authenticated user can see records only from their own region. It is important particularly for displaying the list of records in the current region, not checking whether the user can access/edit a particular single record.
I have looked into Query Scopes, but I am not able to access the currently authenticated user withing them. The only case when I can access the current user is when the global scope is defined in a closure, but this defeats the purpose of not having to define the same logic in each model (i.e. I cannot extract the filtering logic to a query scope class).
What would be a good alternative approach to consider? How can I set the global model filters based on a property of a currently authenticated user?