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

MohamedKamal's avatar

Auth Attempt behavior

I'm building API so it's token based auth, but why this give me the auth user without any token in postman ?

if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
					//it gives me the auth user object
                    dd(auth()->user());

as I know there are no sessions in api.

0 likes
8 replies
vincent15000's avatar

The attempt function only attempt to authenticate the user.

https://laravel.com/docs/10.x/authentication#authenticating-users

Then you have to generate a token to send to the frontend.

You should use the Sanctum package to handle your API, it's a secure package.

https://laravel.com/docs/10.x/sanctum

WIth this package the token is automatically generated and sent to the frontend via axios.

https://laravel.com/docs/10.x/authentication#authenticating-users

MohamedKamal's avatar

@vincent15000 I know all of that, that's not my problem my question is how there auth()->user() returns object of user after Auth::attempt() Although there's no token in request yet, how the app know the authenticated user without any tokens?

1 like
krisi_gjika's avatar

@MohamedKamal "Although there's no token in request yet, how the app know the authenticated user without any tokens" since you attempted to auth the user via email and password, inside this request the user will be authenticated. The token is than used to authenticate the user on other api routes, since there is no session to authenticate the user for you.

1 like
vincent15000's avatar

When you authenticate, the token is generated behind the scene.

vincent15000's avatar

@MohamedKamal The ->createToken() function is used for other situations.

For example if you create an API to provide some datas, but without any frontend and if you want to share these datas with other developers so that they can use them, you can use this function in order that the users create a token. Then they can use this token inside their own backend or frontend to retrieve the datas you provide.

Udev's avatar

Have u added a middleware to protect the route ?

Route::middleware(['auth:sanctum'])->post('/routename', function() {
	//todo
});

Also, you need the token after login so it wouldn't make sense to protect your login route.

Please or to participate in this conversation.