Obtain authenticated user in constructor

1

After much research and a look at documentation , I fully realize that why not make the "old fashioned", but wanted a workaround / solution to do the following:

I have a base class, it is not called directly in the request, it is not declared in the routes:

class AdminPanelController extends Controller
{
    protected $_authUser;

    public function __construct() {
        $this->middleware(function ($request, $next) {
             $this->_authUser = Auth::guard('admin')->user();
             dd($this->_authUser); // tudo bem
             return $next($request);
        });
    }
    ...
    protected function yoo() {
        dd($this->_authUser); // null, mas precisava disto aqui
    }
}

I needed the authenticated user to be available, in the yoo() method, with the controller called directly with the request:

Route::get('users', 'UsersController@hey');

UsersController:

class UsersController extends AdminPanelController 
{

    protected params;

    public function __construct(Request $request) {
        parent::__construct();
        $this->params = $this->yoo(); // auth user é null, mas precisava de chamar o metodo aqui
    }
    ...
}

Note that calling the method $this->yoo() elsewhere than the constructor already works fine, but I really need to call it in the constructor.

NOTE: I also tried $request->user() with result Authentication user provider [] is not defined. , as this is a multiauthentication system would have to define a $request->guard('admin')->user() guard that gave: Method guard does not exist

    
asked by anonymous 29.12.2016 / 12:41

1 answer

0

Try something like this:

class AdminPanelController extends Controller
{
    protected $_authUser;

    public function __construct() {
        $this->middleware([$this, 'getAuthUserFromMiddleware']);
    }

    public function getAuthUserFromMiddleware($request, $next){
        $this->_authUser = Auth::guard('admin')->user();
        return $next($request);
    }

    protected function yoo() {
        return $this->_authUser;
    }
}

class UsersController extends AdminPanelController 
{
    protected params;

    public function __construct(Request $request) {
        parent::__construct();
        $this->params = $this->yoo();
    }
}

Or by putting use in the function:

class AdminPanelController extends Controller
{
    protected $_authUser;

    public function __construct() {
        $this->middleware(function ($request, $next) use($this->_authUser) {
             $this->_authUser = Auth::guard('admin')->user();
             return $next($request);
        });
    }

    protected function yoo() {
       return $this->_authUser;
    }
}
    
29.12.2016 / 13:53