laravellaravel-11

Laravel plainTextToken is null when listing tokens


I am playing with Laravel and Sanctum. I try to use the first token of the user in javascript, but Laravel does not want to convert it into a plainTextToken, it gives me null.

@auth
    @dump(Auth::user()->tokens->first()->plainTextToken) # null
    @dump(Auth::user()->tokens->first()->token) # hexadecimal token
@endauth

Is this a bug or a feature?


Solution

  • When you generate token using createToken() method, it returns a Laravel\Sanctum\NewAccessToken instance.

    API tokens are hashed using SHA-256 hashing before being stored in your database, but you can access the plain-text value of the token using the plainTextToken property of the NewAccessToken instance. You should display this value to the user immediately after the token has been created like this.

    use Illuminate\Http\Request;
     
    Route::post('/tokens/create', function (Request $request) {
        $token = $request->user()->createToken($request->token_name);
     
        return ['token' => $token->plainTextToken];
    });
    

    You are getting this NULL value because you are applying plainTextToken on the DB stored value of the token which is already hashed using SHA-256.

    Check the Issuing API Tokens section of the docs for more information.