Skip to content

Sanctum ​

Add Sanctum when the application needs an API. The Svelte/Inertia frontend already uses session authentication; do not replace that with personal access tokens.

Run commands in the Laravel application. Keep the model changes from User Name Split and Spatie Permissions.

Install ​

bash
php artisan install:api
php artisan migrate

Confirm routes/api.php is registered in bootstrap/app.php. The generated /api/user route should use auth:sanctum.

User Model ​

File: app/Models/User.php (additions)

php
use Laravel\Sanctum\HasApiTokens;

// Inside the existing User class:
use HasApiTokens;

Do not replace the full model. Keep passkeys, two-factor authentication, HasRoles, casts, and split-name methods.

API Access ​

Protect API routes with auth:sanctum; keep resource authorization in policies. Token abilities do not replace ownership checks.

For personal access tokens, return the plaintext token only at creation, set appropriate abilities and expiry, and provide revocation. Keep tokens out of URLs, logs, and Git.

For a separate first-party SPA, follow Sanctum's cookie-based SPA setup (statefulApi, stateful domains, CSRF, and credentialed requests). That is separate from adding token support here.

Verify ​

File: tests/Feature/ApiAuthenticationTest.php

Use the starter's database-refresh test setup. This checks the generated endpoint with a real bearer token, not just Sanctum::actingAs().

php
<?php

use App\Models\User;

test('the API user endpoint requires a valid token', function () {
    $this->getJson('/api/user')->assertUnauthorized();

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

    $this->withToken($token)
        ->getJson('/api/user')
        ->assertOk()
        ->assertJsonPath('id', $user->id);
});
bash
php artisan test --compact tests/Feature/ApiAuthenticationTest.php

Also check that browser login, profile updates, and passkeys still work.

References ​