Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 -> 5.3 Auth::user() returning null

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?

like image 446
Artur Grigio Avatar asked Dec 01 '22 12:12

Artur Grigio


1 Answers

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

like image 137
Ionut Avatar answered Dec 05 '22 22:12

Ionut