4

I've upgraded from 5.2 -> 5.3 and the Auth::user() is returning null.

Route

Route::group(['middleware' => ['auth']], function () { Route::get('/test', 'MyController@showMain'); } 

Controller with constructor calling Auth::check() returns null

public $user; public function __construct() { $this->user = Auth::user(); } public function showMain() { return $this->user; } 

Controller with showMain calling Auth::check() returns User (as expected).

public function __construct() { // Nothing } public function showMain() { return Auth::user(); } 

I've also looked at the difference between a clean install of 5.3 and 5.2->5.3 upgraded. There are 2 extra classes in 5.3 that are not in the upgraded version.

  • Authenticate.php
  • Authorize.php

And these classes are being called by the Kernel.php in protected $routeMiddelware

I've also looked into \Auth::user() is null in 5.3.6?, not only this doesn't solve my specific problem, I also don't think it's a good solution.

Can someone explain to me why am I running into this problem?

1
  • 2
    you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet docs Commented Nov 3, 2016 at 21:36

2 Answers 2

9

Starting with Laravel 5.3 one cannot get the currently logged in user in controller constructor because the middleware has not run yet, but in other controller methods, as you have showMain, there is not problem getting it.

Laravel migration guide excerpt:

In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors

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

1 Comment

Works for me, TY bro!
9

To get access to Auth::user() in the __constructor() (starting with Laravel 5.3) you'll need to run:

public $user; public function __construct() { $this->middleware(function ($request, $next) { $this->user = Auth::user(); return $next($request); }); } 

2 Comments

I upvoted, but beware, this answer doesn't work when you try to grab controller from service container
You just saved my day sir! Works exactly like I wanted. Thankyou :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.