79635824

Date: 2025-05-23 15:45:41
Score: 1
Natty:
Report link

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();

Explanation

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 of self::deleting (Understanding Static vs Self in PHP).

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: lchristmann