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条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: