2

I have a private variable in my class that I want to be set to the authenticated user. For some reason, though, I can't get the variable to be set inside of the constructor. Here is what I have so far:

private $user = null;


  public function __construct()
    {
        $this->middleware('auth');

        $this->user = Auth::user();
    }

 public function index()
    {
        $return['Admin'] = $this->user;

        return view('home', compact('return'));
    }

The variable $user stays null for some reason though. When I use Auth::user() in place of $this->user though, it works just fine. I have set variables from the constructor multiple times in the past and this is the first time it hasn't worked for me. Any help would be appreciated.

1 Answer 1

6

Since Laravel 5.3 you are no longer able to access session in controller constructors, because middleware has not run yet.

You can define a closure (scroll to "Session In The Constructor") that happens after the session middleware has ran.

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

1 Comment

Thank you very much. Works like a charm.

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.