简体   繁体   中英

Laravel 5.6 Access auth()->user() in controller constructor?

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

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.

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;
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM