Laravel: Getting Authenticated User Early in the Controller

Sometimes there is a need to access the authenticated user in your controller.  If you do it in several methods in your controller, it makes sense to put the code in the constructor.  Unfortunately, the code below will not work. This happens because the request is not injected into the controller at the time of its instantiation.

 

    //ToDoController.php
    ...
    public function __construct()
    {
      // Line below will return null for $this->authUser
      $this->authUser = auth()->user();
    }

In other words, in Laravel you have to get the authenticated user at the right time (once request is injected in your controller). To get the authenticated user early on in your controller Taylor Otwell suggests using anonymous middleware, which is a closure, in the constructor.

 

    //ToDoController.php
    ...
    public function __construct()
    {
       $this->middleware(function($request, Closure $next){
          $this->authUser = auth()->user();
          return $next($request);
       });
    }

 

The code above is perfectly fine, because this custom anonymous middleware will run within the middleware stack after the authentication has already taken place. In Laravel you cannot just get the authenticated user whenever you want. You have to be mindful where you are in the lifetime of the request cycle.

 

Share this article

Posted

in

by

Tags: