phplaraveltokenlaravel-passport

Laravel Passport API: createToken get id


Situation

I'm using Laravel Passport API to communicate between Laravel and external "agents" via Personal Access Tokens: https://laravel.com/docs/5.5/passport#personal-access-tokens

You can create tokens: via $token = \Auth::user()->createToken('name')->accessToken;

($token then holds only the token itself, not the object)

Question

How can I get the token()->id for a newly created token?

Background

I need to get the ID to store it in the database to make relation to other table.


Solution

  • You should split the token creation:

    First create the object, this returns a Laravel\Passport\PersonalAccessTokenResult Object:

    $tokenobj = \Auth::user()->createToken('name');

    Then you can get the accessToken itself via:

    $token = $tokenobj->accessToken;

    And the token id via:

    $token_id = $tokenobj->token->id;