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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With