skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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() ;
    
    Login or Signup to reply.
  3. If you have the name of the token, you can get it like this:

    $user = Auth::user();   
    $token = $user->tokens()->where('personal_access_tokens.name', 'your-token-name')->first();
    
           
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search