Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ali254's avatar

Auth::guard('admin')->user() returns NULL

hi. i logged in with the attempt (admin guard) method and a session is also created. but in my controller Auth::user , return null .

I've dedicated Middleware "auth:admin" to that Route. I just created a provider named admin and guard admin, do I need to make other settings? Thanks

0 likes
12 replies
ali254's avatar

@stefverniers I have a user table and an admin table. I created an admin guard for the admin table, and now I want to access the features of that table, but it returns empty.

ali254's avatar

@stefverniers

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],


'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],

Route::prefix('dashboard/admin/brand')->middleware(['auth:admin'])->group(function () { Route::get('/view', [BrandController::class, 'BrandView'])->name('all.brand'); });

public function __construct()
{
    dd (Auth::guard('admin')->user());   //return null

}

ali254's avatar

@stefverniers

dd (Auth::user()); //return null.

dd (Auth::guard('admin')->guest()); //return true

I think the problem is with middleware.

Snapey's avatar
Snapey
Best Answer
Level 122

you cannot obtain the authenticated user within the __construct() method. Controllers are initiated before the authentication is performed.

Test from within a controller method.

It is possible to access the user model within the constructor via a middleware. If you needed to setup some controller attributes, you can do it like;

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

The middleware is registered when the constructor runs, and then the code inside the callback is executed when middlewares are executed later.

3 likes
ali254's avatar

Yes! The problem is with the constructor method! Thanks a lot

Please or to participate in this conversation.