Laravel Sanctum Tokens with Remember Me

March 11th, 2022

Publish the sanctum migration.

1php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Then update the file to include a remember boolean column.

1// database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php
2 
3...
4$table->boolean('remember')->default(false);
5...

Set the expiration in the sanctum config file to how long you want the tokens to expire without remembering the user.

1// config/sanctum.php
2 
3'expiration' => 60 * 24 * 2, // 2 day(s)

Within the boot method of a Service Provider, we need to update how a token is checked to be valid. The third clause using the last_used_at column is optional, allowing a token to only become invalid after they were last used and not from when they were created.

1use Laravel\Sanctum\Sanctum;
2use Laravel\Sanctum\PersonalAccessToken;
 3 
 4...
5Sanctum::authenticateAccessTokensUsing(function (PersonalAccessToken $token, $isValid) {
6 return $isValid
7 || $token->remember
8 || $token->last_used_at->gt(now()->subMinutes(config('sanctum.expiration')));
 9});
10...

Now when creating a token, the remember column should also be set.

1$token = $user->createToken($request->token_name);
2$token->accessToken->remember = $request->remember_me;
3$token->accessToken->save();