donglv6960 2017-12-06 02:20
浏览 58
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • duanmu2013 2017-12-06 13:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大