Laravel Passport Print Personal Access Token

Minion picture Minion · Jan 9, 2017 · Viewed 13.5k times · Source

I am using Laravel's passport package to provide token based authentication to my rest api. Right now, I am using personal access token concept to generate the access token.

To generate an access token for a single user, I am using below code to generate a token with name 'android'.

    $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);

    // Here the access token will be stored in $token variable.
    $token = $user->createToken('android')->accessToken;

    // Now the $token value would be something like
   //eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImMyNjI3YzU0YjFhNWIxZTFlMTdkODhmZTk1NzhjNzAzY2QyMTU0MzhlOD...

Later on I want to display the personal access token on my admin dashboard which I am facing difficulty in getting the generated token again. Tried below code, but couldn't able to get the access token.

$user = User::find(1)
dd($user->tokens())

I also tried using passport vue elements, but it is displaying just the access token name, not the actual token.

<passport-personal-access-tokens></passport-personal-access-tokens>

Please help me getting this solved.

Thank you

Answer

Serg Chernata picture Serg Chernata · Jan 12, 2017

I think you should just generate the token before or at the same time as you're creating a user and store it in the database:

Add the column:

$table->string('token', 60)->unique();

Save the token:

$token = $user->createToken('android')->accessToken;

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
    'token' => $token,
]);

Then it will be available as:

$user->token;