Creating global permissions variable after user authorization in Laravel

693 views Asked by At

I would like to set global variable after the user is authenticated - lets call it permissions. The variable should be available in controllers and views.

What is the best way to achieve it? Now in each method I have to perform database query and check user roles which is not optimal.

I know that I can declare view::share method in appserviceprovider to pass the variable to views, but boot method is performed after the user is authenticated.

Update

I've created BaseController which extends from Controller.

BaseController:

class BaseController extends Controller {

  public $permissions;

  public function __construct() {
      $this->permissions = GroupRoles::where('id', Auth::user()->id)->first();
  }

}

Then I'm trying to access the permissions variable from UserController which extends from BaseController. Getting the trying to get access of non-object. I think it's because the BaseController constructor is contructed before the middleware.

class UserController extends BaseController {

  public function showPermissions() {
    return var_dump($this->permissions);
  }

}

The final solution

The cornerstone was to use the $this->middleware(function ($request, $next) in the BaseController.

1

There are 1 answers

3
Petyo Tsonev On BEST ANSWER

Try it within the controller or create your own BaseController then extend your controllers from it and in the BaseController you can do like this

public $permissions;

public function __construct()
{
   $permissions = Permissions::all() //For example
   $this->permissions = $permissions
}

Then you can access it from every controller like this $this->permissions