7

I am trying to access auth()->user() in controller constructor, but it always return null.

I have tried below, but no luck!

protected $user;

function __construct() {
    $this->middleware(function ($request, $next) {
        $this->user = auth()->user();

        return $next($request);
    }); 

}

Is there any way to do this?

--Thanks

Kalim
  • 487
  • 6
  • 18

3 Answers3

4

Controller Constructor is called before Middlewares. So you can not get User information inside Constructor().

My advice is create private function that sets User, and call this inside your functions.

Ts8060
  • 1,030
  • 8
  • 19
0

Thanks to @Ts8060 i had the idea to create a singleton for doing that.

/** @var User */
private static $user;

/**
 * Singleton
 *
 * @return User
 */
public function getUser() {
    if(empty(static::$user)) {
        static::$user = Auth::user();
    }

    return static::$user;
}
-2

I think that auth middleware run after create controller, you may do somethink like this in your controller

public function callAction($method, $parameters)
{
    $this->middleware(function ($request, $next) {
       $this->user = auth()->user();

       return $next($request);
    }); 

    return parent::callAction($method, $parameters);
}
J. Doe
  • 1,682
  • 11
  • 22