Sanctum is Laravel's simple way to protect APIs used by mobile apps and JavaScript frontends. It is installed by php artisan install:api.
How token login works
- The app sends email and password to
POST /api/login - Laravel checks them and creates a token
- The app stores the token and sends it with every request in the header
Authorization: Bearer <token> - Routes inside
auth:sanctumaccept only valid tokens
Setup
Add the HasApiTokens trait to the User model. Tokens are stored (hashed) in the personal_access_tokens table.
Creating and deleting tokens
$user->createToken('mobile-app')->plainTextToken— the token string to send to the app (shown only once)$request->user()->currentAccessToken()->delete()— log out this device$user->tokens()->delete()— log out everywhere
Token abilities
Limit a token: createToken('app', ['posts:read']), then check $request->user()->tokenCan('posts:read').
For a frontend on the same domain (such as a Vue or React SPA), Sanctum can use secure cookie sessions instead of tokens.
Example
<?php
// routes/api.php
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
Route::post('/login', function (Request $request) {
$request->validate(['email' => 'required|email', 'password' => 'required']);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages(['email' => 'Wrong email or password.']);
}
return ['token' => $user->createToken('mobile-app')->plainTextToken];
});
Route::middleware('auth:sanctum')->group(function () {
Route::get('/me', fn (Request $request) => $request->user());
Route::post('/logout', function (Request $request) {
$request->user()->currentAccessToken()->delete();
return response()->noContent();
});
});
POST /api/login returns {"token":"1|abc..."}. GET /api/me with the header Authorization: Bearer 1|abc... returns the user as JSON; without it, the response is 401 Unauthenticated.