Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TotoalNormie's avatar

Call to undefined method App\Models\User::token()

I am testing my auth api that is built on Laravel Sanctrum. In the test i am using Sanctrum::actingAs method, and it gives this error:

Call to undefined method App\Models\User::token()

By the way, I already have HasApiTokens in my User model. I have tried a lot, but still haven't figured it out. Your help would be very appreciated.

For refference, this is the Pest test:

it('logs out', function () {
    $user = User::factory()->create();
    Sanctum::actingAs($user, ['*']);

    $response = $this->postJson('/api/auth/logout');

    $response->dump();

    $response->assertSuccessful();


    $this->assertCount(0, $user->tokens);
});

0 likes
8 replies
SarwarAhmed's avatar

php artisan config:publish cors

dd($user->tokens);

TotoalNormie's avatar

@SarwarAhmed This is the output:

Illuminate\Database\Eloquent\Collection^ {#3720
  #items: []
  #escapeWhenCastingToString: false
} // tests/Feature/AuthTest.php:37
Snapey's avatar

can you show your user model and user factory?

TotoalNormie's avatar

@Snapey

Snapey's avatar

@TotoalNormie

Did you do this bit?

Then, you may instruct Sanctum to use your custom model via the usePersonalAccessTokenModel method provided by Sanctum. Typically, you should call this method in the boot method of your application's AppServiceProvider file:

experimentor's avatar

@totoalnormie, I think the error is pointing to something in your controller code. Could you please show the code (controller code) being executed for this route?

POST '/api/auth/logout'
shaungbhone's avatar

I think you need to create token first. Otherwise the Sanctum::actingAs() method doesn’t actually create tokens in the database.

$user = User::factory()->create();
$token = $user->createToken('Test Token')->plainTextToken;

Sanctum::actingAs($user, ['*']);

$response = $this->postJson('/api/auth/logout');

$response->assertSuccessful();

// Reload the user to check for tokens
$user->refresh();
$this->assertCount(0, $user->tokens);

Please or to participate in this conversation.