Little late, but anyway someone might find it useful.
Instead of setting up a CRON job, you can use the passport events for this. Passport emits events when access token is created and when the refresh token is created. All you need to do is to register this events in the EventServiceProvider
and then call php artisan event:generate
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Laravel\Passport\Events\AccessTokenCreated' => [
'App\Listeners\RevokeOldTokens',
],
'Laravel\Passport\Events\RefreshTokenCreated' => [
'App\Listeners\PruneOldTokens',
],
];
Then in App\Listeners\PruneOldTokens
you can delete every other token that the user had before:
/**
* Handle the event.
*
* @param AccessTokenCreated $event
* @return void
*/
public function handle(AccessTokenCreated $event)
{
Token::where([
['user_id', $event->userId],
['id', '<>', $event->tokenId]
])->delete();
}
Don't forget to import Laravel\Passport\Token
at the top.
Note: I'm also deleting expired refresh tokens on the refresh token created event. Just add this in the listener for the refresh token created event. This way, every time a new refresh token is created for some user, all expired tokens are deleted.
/**
* Handle the event.
*
* @param RefreshTokenCreated $event
* @return void
*/
public function handle(RefreshTokenCreated $event)
{
\DB::table('oauth_refresh_tokens')
->whereDate('expires_at', '<', now()->addDays(1))
->delete();
}