Authentication with Laravel Sanctum
Issue and validate API tokens using Sanctum for SPA and mobile clients.
Authentication with Laravel Sanctum is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is Sanctum?
Laravel Sanctum provides a simple token-based authentication system for SPAs and mobile clients. It supports both API tokens and session-based authentication for first-party SPAs.
Installing Sanctum
Install and configure Sanctum.
$ composer require laravel/sanctum
$ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
$ php artisan migrateIssuing Tokens
Generate a personal access token for a user after verifying credentials.
<?php
Route::post("/login", function (Request $request) {
$request->validate(["email" => "required", "password" => "required"]);
$user = User::where("email", $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
"email" => ["The provided credentials are incorrect."],
]);
}
$token = $user->createToken("mobile-app")->plainTextToken;
return response()->json(["token" => $token]);
});HasApiTokens Trait
Add the HasApiTokens trait to your User model to enable token management.
<?php
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}Protecting Routes
Use the auth:sanctum middleware to protect API routes.
<?php
// routes/api.php
Route::middleware("auth:sanctum")->group(function () {
Route::get("/user", fn(Request $r) => $r->user());
Route::apiResource("posts", PostController::class);
});Sending the Token
Clients send the token in the Authorization header as a Bearer token.
# HTTP header:
Authorization: Bearer 1|AbCdEf1234567890...Token Scopes (Abilities)
Assign abilities to tokens to restrict what actions they can perform.
<?php
// Create token with abilities:
$token = $user->createToken("mobile", ["read:posts", "write:comments"])->plainTextToken;
// Check ability:
if ($user->tokenCan("write:comments")) {
// allowed
}Revoking Tokens
Delete a specific token or all tokens (logout all devices).
<?php
// Revoke current token (logout):
$request->user()->currentAccessToken()->delete();
// Revoke all tokens (logout everywhere):
$request->user()->tokens()->delete();Token Expiration
Set token expiry in config/sanctum.php. Tokens are checked against last_used_at and the expiry window.
// config/sanctum.php
"expiration" => 60 * 24 * 7, // 7 days in minutesSPA Authentication
For same-domain SPAs, Sanctum can use session-based auth instead of tokens. Call /sanctum/csrf-cookie first, then use normal login.
Sanctum vs Passport
Sanctum: simple API tokens and SPA auth. Passport: full OAuth2 server with authorization codes, client credentials, and refresh tokens. Start with Sanctum; only move to Passport if you need OAuth2.
Summary
Sanctum issues Bearer tokens for API auth. Add HasApiTokens to the User model. Protect routes with auth:sanctum. Revoke tokens on logout. Use abilities to scope permissions.
Quick Check
How does a client include a Sanctum token in API requests?
Frequently asked questions
Is the “Authentication with Laravel Sanctum” lesson free?
Yes — the full text of “Authentication with Laravel Sanctum” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Authentication with Laravel Sanctum”?
Issue and validate API tokens using Sanctum for SPA and mobile clients. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Authentication with Laravel Sanctum” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- API Routes and Resource Controllers
- API Resources and JSON Responses
- Authentication with Laravel Sanctum
- Rate Limiting and API Versioning