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?
CodePudding user response:
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-tokens
CodePudding user response:
You may access all of the user's tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:
auth::user()->tokens
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
auth::user()->tokens->first() ;