Filter user's access on request based on Laravel's model

ⅰ亾dé卋堺 提交于 2019-12-25 00:41:02

问题


I have a table full of Products. But, for each user is only allowed a group of Products to see. This is done by the table users_products_permissions. Each user has an instance of UsersPermissions table. In this table I set a range of restrictions to be applied on the user, restrictions to say each product a user is allowed to "see". This is done by a 'weak' (That's how we call in brasilian portuguese) table composed only by user_permission_id and product_id.

By the time of the requesition the requester user will be logged, of course.

The questions rests on: How to filter user's access to products based on it's restrictions?

Without checking in every requisition, manually, if the user model have access to this product. An automatic way, lets say...

In case any code is needed, just say it!


回答1:


For 4.2: Use a global scope to scope an entire model.

http://laravel.com/docs/4.2/eloquent#global-scopes and http://softonsofa.com/laravel-how-to-define-and-use-eloquent-global-scopes/

For 4.0: http://www.laravel-tricks.com/tricks/global-scope-model and Laravel Eloquent Query Builder Default Where Condition

<?php

class Product extends Eloquent {

    public function newQuery()
    {
      return parent::newQuery()->where('permission', '=', 1);
    }
}



回答2:


You can use a Query Scope for this. Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

class User extends Eloquent {

    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }

}

Utilizing A Query Scope

$users = User::popular()->women()->orderBy('created_at')->get();


来源:https://stackoverflow.com/questions/28372717/filter-users-access-on-request-based-on-laravels-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!