Laravel Passport provides a simple way to handle API authentication using OAuth2. When issuing personal access tokens, you may need to store extra properties—such as an API version number alongside the token. In this post, we'll explore how to achieve this in Laravel Passport.

By default, Laravel Passport stores tokens in the oauth_access_tokens table. However, it does not provide a built-in way to store additional metadata.

Fortunately, we can modify the token creation process to include custom properties.

When issuing a new personal access token, you can store extra metadata using the token model. Here’s how:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\PersonalAccessTokenResult;

public function storePersonalAccessToken(Request $request): PersonalAccessTokenResult
{
    return DB::transaction(function () use ($request) {
        $tokenResult = $request->user()->createToken(
            $request->name,
            $request->scopes ?: []
        );

        $tokenResult->token->forceFill([
            'api_version' => 'v1.0',
        ])->save();

        return $tokenResult;
    });
}

We're wrapping this in a database transaction to ensure that if the update of the API version fails, no token will be craeted.

Later, you can retrieve this custom field from the authenticated user’s token:

$token = auth()->user()->token();
$apiVersion = $token->api_version;

Since Laravel Passport does not include an api_version column by default, we need to modify the oauth_access_tokens table.

Run the following command to create a migration:

php artisan make:migration add_api_version_to_oauth_access_tokens --table=oauth_access_tokens

Modify the migration file:

public function up()
{
    Schema::table('oauth_access_tokens', function (Blueprint $table) {
        $table->string('api_version')->nullable();
    });
}

public function down()
{
    Schema::table('oauth_access_tokens', function (Blueprint $table) {
        $table->dropColumn('api_version');
    });
}

Run the migration:

php artisan migrate

With these changes, Laravel Passport personal access tokens can now store additional metadata, such as API versioning. This approach ensures that your application can manage versioned API access more effectively while maintaining full compatibility with Laravel Passport.