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

时间:2018-07-24 10:18:43

标签: php laravel laravel-5.6

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

3 个答案:

答案 0 :(得分:0)

Controller构造函数在中间件之前被调用。因此,您无法在Constructor()中获取用户信息。

我的建议是创建设置用户的私有函数,然后在函数内部调用它。

答案 1 :(得分:0)

感谢@Ts8060,我有了为此创建一个单例的想法。

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

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

    return static::$user;
}

答案 2 :(得分:-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);
}