Kalim
Kalim

Reputation: 499

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

Upvotes: 7

Views: 4269

Answers (3)

Fernando R. Rinaldi
Fernando R. Rinaldi

Reputation: 1

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

Upvotes: 0

Ts8060
Ts8060

Reputation: 1070

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.

Upvotes: 4

J. Doe
J. Doe

Reputation: 1732

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

Upvotes: -2

Related Questions