drsc10888 2017-05-21 09:28
浏览 91
已采纳

Laravel控制器具有角色

I have an application which will be a SaaS and is utilizing user roles. Of course, controllers will need to forward different data depending on user roles or permissions, however I think this approach may lead me to huge controllers and I was wondering if there is a smarter way to do this? For example my user create method:

public function create()
{
    if (Auth::user()->isAdmin()) {
        $clinics = Clinic::pluck('name', 'id');
        $roles = Role::pluck('display_name', 'id');
    }
    else{
        $clinics = Clinic::where('id', Auth::user()->clinic_id)->get()->pluck('name', 'id');
        $roles = Role::where('name', '!=', 'admin')->get()->pluck('display_name', 'id');
    }

    $states = State::pluck('name', 'id');
    $cities = City::pluck('name', 'id');

    return view('users.create', compact('user', 'clinics', 'states', 'cities', 'roles'));
}

Which is okay now when I only implemented admin and non-admin user, but when roles get complicated, is there a cleaner way to assemble this?

  • 写回答

1条回答 默认 最新

  • duanji2014 2017-05-21 09:52
    关注

    I suggest you to take a look to the Scopes of the Laravel Documentation. You can attach the scopes to your models to achieve the same results.

    This solution will not help you deleting code complexity (that is moved in models) but will help you remove code duplication because you will encounter the same "if" multiple times during the development of your application...

    A local scope for your clinics could be like this one

    class Clinic extens Model {
        [...]
        public function scopeCanSee($query)
        {
            $user = Auth::user();
            if(!$user->isAdmin())
                return $query->where('id', $user->clinic_id);
            return $query;
        }
    }
    

    and in your controller you can then filter the results in this way

    public function create()
    {
        $clinics = Clinic::canSee()->pluck('name', 'id');
        [...]
    
        $states = State::pluck('name', 'id');
        $cities = City::pluck('name', 'id');
    
        return view('users.create', compact('user', 'clinics', 'states', 'cities', 'roles'));
    }
    

    Global Scopes

    Another way is to use the Global Scopes (but I haven't tested them)

    class Role extends Model
    {
        protected static function boot()
        {
            parent::boot();
            static::addGlobalScope(new RolesScope);
        }
    }
    class Clinic extends Model
    {
        protected static function boot()
        {
            parent::boot();
            static::addGlobalScope(new ClinicsScope);
        }
    }
    

    and scopes similar to

    class ClinicsScope implements Scope
    {
        public function apply(Builder $builder, Model $model)
        {
            $user = Auth::user();
            $builder->where('id', $user->clinic_id);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?