Placid
2 years ago

Authorizing in Controller Constructor

Posted 2 years ago by Placid

Hello,

Is it possible to authorize an action in the constructor of a controller so that every method will check the authorization before implementing the method?

I have defined a Gate as follows:

Gate::define('manage-users', function($user) {
        return $user->user_level_name == "super_admin" || $user->user_level_name == "admin";
});

This authorization will be checked for every method in UserController. It works perfectly if I include in individual methods, such as:

public function create()
{
        $this->authorize('manage-users');
        $user_levels = UserLevel::all();
        return view('users.create', compact('user_levels'));
}

But when I put the check in the constructor it blocks any user from accessing any method in the controller.

Is there any way to do this, or do I have to repeat the same check in every method in the controller.

Please sign in or create an account to participate in this conversation.