I’m using Laravel Sanctum v3 in my Laravel project. I have an API controller which has the auth:sanctum
middleware attached to it. I’m using the API key/plain access token that I copied to authenticate myself, but I need to retrieve the corresponding token itself.
I thought I could just do this from within my controller:
return response()->json([
'token' => Auth::user()->token
], 200);
This gives me:
The attribute [token] either does not exist or was not retrieved for model
I also tried doing:
PersonalAccessToken::find(Auth::id());
This gives me null
What am I missing?
3
Answers
I guess what you are looking for is
Auth::user()->tokens
which will return array of tokens to you. See the documentation : https://laravel.com/docs/9.x/sanctum#issuing-api-tokensYou may access all of the user’s tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:
will return a collection of tokens related to the auth user
if u don’t Create an access token without a specific ability (Abilities serve a similar purpose as OAuth’s "scopes")
u can just do like that
If you have the name of the token, you can get it like this: