Home > Software design >  Laravel returing null when attempting to read the authenticated user
Laravel returing null when attempting to read the authenticated user

Time:12-03

So I am using laravel api.php for API routing. But I cant figure out why it does not let me use the session. I know api.php depends on token but I need the session to verify user id & co. Beside that when I try to group the routing in auth.php with the auth I get `"Unauthorized".

I have tried to add

\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\EncryptCookies::class,

in Kernel.php where the api is but it did not work. I even added the guard when getting the user: auth('api')->user() or auth()->guard('api')->user() but unfortunately it did not work. My goal is to get the auth()->user() when using the API routes.

My api.php

php
Route::post('/doSomething', \[App\\Http\\Controllers\\ProductController::class, 'doSomething'\])

My DoSomethingController.php

function doSomething(Request $request) {
    Log::info(auth()->user()->user_id) // Is empty
}

My config/auth.php

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

The error I get when I do auth()->user()->user_id:

Attempt to read property "user_id" on null

CodePudding user response:

Maybe this usage is wrong.

auth()->user()->user_id;

Can you try this

Auth::user()->user_id;

CodePudding user response:

So yeah I dont know why it fix the problem but in Kernel.php I included this too

\Illuminate\View\Middleware\ShareErrorsFromSession::class, and it somehow worked.

So at last it looks like this:

'api' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        
        \Illuminate\Routing\Middleware\SubstituteBindings::class,            
    ],
  • Related