I am working on a control panel app 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 perform all Restful methods, while an editor can only View and Update a user.
I know that entrust comes with middlewares out of the box, which is perfect for what i need. But it works on the routes only (in which case i would need 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 a middleware in the constructor that would check for user role and then only allow to use the method only if the role has permission to use it. But this should be done in a decent way without any hacks because i will be using it on other controllers as well.
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 middlewares provided by Entrust as base and retrieve the called method, e.g. if you use 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 extract the called method and still need to implement retrieveRequiredRolesForMethod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With