0

I have a ajax function which call a controller listed on api.php (route).

Inside this controller, I'm trying to make a user's log. So, I need to store the id user in a log table. But, when I try to access any method of Auth::user(), even being logged in, I get the exception "Unauthenticated".

I think It's a miss of sending some header information on ajax function.

Someone could help me, please?

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17

3 Answers3

4

If I am correct, api.php routes in laravel are set to uses tokens rather than the session. This means each call will require a token (specified on the user model/record) to be passed.

Using Auth::user() within web.php will work as that uses user sessions to authenticate.

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17
  • 1
    Yes that is correct. Within the web middleware group sessions are started but not in the API middleware group. Therefore within the API routes it is not possible to retrieve the authenticated user from the session. – George Hanson Jun 25 '19 at 15:12
0

You can try this one,

In your Kernel.php file add your own name like 'sessions' to the $middlewareGroups. It should contain \Illuminate\Session\Middleware\StartSession::class

Assign 'sessions' to those routes you want.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],

    'sessions' => [
        \Illuminate\Session\Middleware\StartSession::class,
    ]
];

routes/api.php

Route::group(['middleware' => ['sessions']], function () {
    Route::resource(...);
});

I think it must work for you

Levon Babayan
  • 266
  • 2
  • 18
-1
<?php echo Auth::user() ?>


or {{Auth::user()->(id)}}
  • Can you explain that further? The OP already stated that calling `Auth::user()` triggers an exception - I don't see that your code covers this after all – Nico Haase Jun 25 '19 at 21:40