hanachan1026
hanachan1026

Reputation: 335

Laravel auth::guard('web')->user() is null in auth middleware

I put myRoute inside the auth middleware group and I get

// myController
Auth::guard('web')->user()  // null

I dont know what to do.. I have controllers and routes below.

Seems like parent controller constructor is working but the middleware is not.

// Controller.php
public function __construct() {
    $this->middleware(function ($request, $next) {
        $this->currentUser = Auth::guard('web')->user();

        return $next($request);
    });
}

// myController extends Controller
public function __construct(Request $request) {
    parent::__construct();
    $this->request = $request;
    var_dump($this->currentUser); // null
    var_dump(Auth::guard('web')->user); // null
    // $userId = Auth::guard('web')->user()->id;
    // $userId = $this->currentUser->id;
    $this->userId = $userId;
}

// route/web.php
Route::middleware(['auth'])->group(function () {
    Route::get('myRoute', 'myController@index');
}

Upvotes: 0

Views: 1541

Answers (1)

Yusuf Eka Sayogana
Yusuf Eka Sayogana

Reputation: 401

You can't get the Auth::user() in constructor. try Auth::guard('web')->user(); in another method. The result is not null anymore

Upvotes: 3

Related Questions