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->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).