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

9
  • Are you use auth middleware on this route? Commented Jul 24, 2018 at 10:19
  • yes, it's bind in routes Commented Jul 24, 2018 at 10:20
  • here it is Route::group(['middleware' => ['auth', 'web']], function () {Route::resource('users', 'UsersController');}); Commented Jul 24, 2018 at 10:23
  • Did you have tried \Auth::user()? Commented Jul 24, 2018 at 10:27
  • 1
    Yes, I have tried all things, always get null value Commented Jul 24, 2018 at 10:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

why will this code work? where do I put this code? please elaborate
-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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.