To add additional information to a Sanctum API token, such as an IP address, you can use the personal_access_tokens table to store custom data. While Sanctum does not natively support adding arbitrary data directly into the token itself, you can leverage the tokenable relationship to store and retrieve additional information.
Here's a step-by-step guide on how to achieve this:
Create a Migration to Add Custom Fields:
First, create a migration to add a custom field to the personal_access_tokens table. For example, you can add an ip_address column.
// database/migrations/xxxx_xx_xx_xxxxxx_add_ip_address_to_personal_access_tokens_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddIpAddressToPersonalAccessTokensTable extends Migration
{
public function up()
{
Schema::table('personal_access_tokens', function (Blueprint $table) {
$table->string('ip_address')->nullable();
});
}
public function down()
{
Schema::table('personal_access_tokens', function (Blueprint $table) {
$table->dropColumn('ip_address');
});
}
}
Run the migration:
php artisan migrate
Create the Token with Additional Information:
When creating the token, you can now store the IP address in the personal_access_tokens table.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function createTokenWithIp(Request $request)
{
$user = Auth::user();
$token = $user->createToken('token-name');
// Store the IP address
$token->accessToken->forceFill([
'ip_address' => $request->ip(),
])->save();
return response()->json(['token' => $token->plainTextToken]);
}
Retrieve the Token with Additional Information:
When you need to retrieve the token and its additional information, you can access the personal_access_tokens table.
use Laravel\Sanctum\PersonalAccessToken;
public function getTokenInfo($tokenId)
{
$token = PersonalAccessToken::find($tokenId);
if ($token) {
return response()->json([
'token' => $token->token,
'ip_address' => $token->ip_address,
// Add other fields as needed
]);
}
return response()->json(['message' => 'Token not found'], 404);
}
By following these steps, you can store and retrieve additional information, such as an IP address, associated with a Sanctum API token. This approach leverages the existing database structure and relationships provided by Sanctum.