Need suggestions on using Entrust roles in one resource controller - Laravel5

I am working on a dashboard application where I have several user roles like globaladmin, editors, etc. Now I want to use these roles with a single UserController resource.

For example, globaladmins should be able to execute all Restful methods, while the editor can only view and update the user.

I know that trust comes with middlemen out of the box, which is perfect for what I need. But it only works on routes (in this case, I will need a separate controller for each role) .

My UserController looks something like this.

Class UserController extends BaseController { $protected $viewfolder; public function __construct { // Checking for role and then assigning the folder name of the views $role = User::getRole(); switch($role) case 'globaladmin': $this->viewfolder = 'globaladmin'; break; case 'editor': $this->viewfolder = 'editor'; break; default: abort(401, 'Access Denied'); break; } public function index(){ if( Entrust::can('view-all-users') ){ $users = User:all(); } return view( $this->viewfolder.'.users.viewuser', compact('users')); } public function create() public function update() public function delete() } 

I need middleware in the constructor that will check the user role, and then allow this method to be used only if the role has permission to use it. But this should be done in a good way without any hacks, because I will use it on other controllers as well.

+8
php laravel-5 acl user-roles
source share
2 answers

I assume that you are using the following in your routes file:

 Route::resource('users', 'UserController'); 

In this case, I would suggest that you use one of the intermediates provided by Entrust as the base and retrieve the called method, for example. if you are using EntrustRole:

 public function handle($request, Closure $next) { $controllerMethod = Route::segment(3); $roles = $this->retrieveRequiredRolesForMethod($method); if ($this->auth->guest() || !$request->user()->hasRole(explode('|', $roles))) { abort(403); } return $next($request); } 

Of course, this is just a hint, and you should find a better way to retrieve the called method and still need to implement retrieveRequiredRolesForMethod

+4
source share

Ah .. I think it will work in your case.

 class UserController extends Controller { public function __construct() { $this->middleware('permission:user_index', ['only' => ['index']]); $this->middleware('permission:user_create', ['only' => ['create', 'store']]); $this->middleware('permission:user_edit', ['only' => ['edit', 'update']]); $this->middleware('permission:user_delete', ['only' => ['delete']]); $this->middleware('permission:user_view', ['only' => ['show']]); } } 

Here user_index, user_create, user_edit, etc. - These are permissions (entries in the name field of the permissions table) for the user module.

This will automatically check the login capability and display the page accordingly.

0
source share

All Articles