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

SimonAngatia's avatar

How to get Authenticated user in API Route

I am trying to access an authenticated user but it is returning an empty object.

The auth()->user() returns an empty object

I have tried someone's suggestion of creating the API route in the web.php file then use web auth middleware but when I send a request to that route, instead of it saving the data into the database, it returns the login page. How do I go about this?

Web API route:

Route::prefix('api')->middleware('auth')->group(function () {
 Route::post('v1/B2C/transaction/result', 'B2CMpesaController@BzCMpesaResult');
});

It returning the login page when I send a request through postman

0 likes
10 replies
Sinnbeck's avatar

What are you using to authenticate your API? Sanctum?

Be aware that api routes does not sessions, so no user session is stored.

SimonAngatia's avatar

It is not an API. I receive data through post, and I have to save that data in the database. Now I am trying to get the logged in User through auth()->user() but that is returning null. The data comes through a request

SimonAngatia's avatar

So there's no way I can get the logged in user's data?

Sinnbeck's avatar

Then dont use api routes. Just use your web.php. Or add a new route type for your new endpoints :)

I wouldn't suggest changing the api routes, as you might need them later in the project lifetime

Otherwise you could just use the token to look up the user in the database?

SimonAngatia's avatar

But even with web.php, when I try posting data, I get page expired error when I try to add the route in the exempted routes in VerifyAuthToken middleware, I again can't access the auth()->user() object.

Sinnbeck's avatar

Ok lets start over. Are you using tokens to authenticate the user, or username and password? And are you using the plain API auth or Laravel Passport?

SimonAngatia's avatar

Well, let's say you are doing payment API integration, where after successful payment, the API sends data to your callback URL. Now of course you what to save that data under the user who did that transaction. So how do you get the user_id if the response data is sent through an API route? That's the situation I am in

jlrdw's avatar

What payment gateway are you using. Because their API should have some tutorials.

Please or to participate in this conversation.