Sunday, May 21, 2017

Laravel controllers with roles

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?



via Norgul

Advertisement