基于当前已验证用户的模型过滤器

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?

I posted a similar question as a possible bug (was not sure whether this behavior was something expected) on Laravel Framework issue tracker on GitHub and found the answer there.

Turns out, you cannot access the authenticated user in the global query scope constructor, but it is accessible in the apply() method.

So instead of:

public function __construct() {
    $this->region_id = Auth::user()->region_id;
}

public function apply(Builder $builder, Model $model)
{
    $builder->where('region_id', $this->region_id);
}

I had to do:

public function apply(Builder $builder, Model $model)
{
    $region_id = Auth::user()->region_id;

    $builder->where('region_id', $region_id);
}

Link to the issue on GitHub here.

How about make a RegionalModel and extend all your Models with a region_id field? Then, in your RegionalModel create a scope like forUser(User $user) to apply your filter.

class RegionalModel extends Model {

    public function scopeForUser($query, User $user) {
        // Apply filter here
    }

}

Then your Customer model might look like this

class Customer extends RegionalModel {

    // Code here

}

Then when you want to get a list of customers

$user = Auth::user();
$customers = Customer::forUser($user)->get();