Laravel Sanctum: API Authentication
Laravel Sanctum: API Authentication
Laravel Sanctum: API Authentication
Tip: Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Gotcha: SPA Authentication
Sanctum uses cookie-based sessions for SPAs. No tokens needed.
Tip: Token-Based Auth
$token = $user->createToken('my-app')->plainTextToken;
Gotcha: Protect Routes
Route::middleware('auth:sanctum')->get('/user', fn() => auth()->user());
Tip: Token Abilities
$user->createToken('token-name', ['posts:create', 'posts:update']);
Gotcha: Revoke Tokens
$user->tokens()->delete();
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
Sanctum is the right choice for most Laravel API authentication needs, but the token-based approach has nuances. I've seen tokens stored in plaintext in mobile app source code (a security disaster) and tokens issued with infinite expiration (a compliance nightmare). Always set token expiration, rotate tokens on password changes, and use the abilities() method to scope permissions. For first-party SPA authentication, use Sanctum's cookie-based approach, not tokens.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)