Using Laravel Sanctum it seems tedious, that you must always explicitly revoke the personal access tokens, when deleting a user:
$user = User::find(123);
$user->tokens()->delete(); // Delete Sanctum tokens
$user->delete();
In my use case, all three commands have to be executed manually by an administrator via Laravel Tinker.
How can the access token deletion be automated?
My desired outcome is this code to be sufficient (implicitly deleting all sanctum tokens of this user):
User::find(123)->delete();
The most straightforward approach is to hook into the deleting
event of the User Eloquent model and delete the Sanctum tokens there.
// app/Models/User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
protected static function booted(): void
{
self::deleting(function (User $user) {
$user->tokens()->delete();
});
}
}
Now your proposed line will work as expected, no need to call $user->tokens()->delete()
explicitly anymore:
User::find(123)->delete();
We use the static booted method on our User
Eloquent model. Within this function, you can listen for various model events, such as creating, updating, and deleting.
Defining an event listener as a closure, we listen for the deleting
event, which is performed before the user is deleted and delete the user's Sanctum tokens on that occasion.
Note: if you extend the User model with child classes and still want this behavior, you'll want to use
static::deleting
instead ofself::deleting
(Understanding Static vs Self in PHP).