agyanadda@gmail.com

Laravel API Authentication with Sanctum

Forms, Security and APIs 1 min read Updated Dec 2, 2026 Topic 24 of 31

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

  1. The app sends email and password to POST /api/login
  2. Laravel checks them and creates a token
  3. The app stores the token and sends it with every request in the header Authorization: Bearer <token>
  4. Routes inside auth:sanctum accept 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

Example — Login, protected route and logout PHP
<?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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which header sends a Sanctum token?

Exercise 2 True / False

The plain text token can be read again later from the database.

Exercise 3 Fill in the Blank

Protect API routes with the auth:___ middleware.

Frequently Asked Questions

Sanctum is a simple token and SPA authentication system, and it is enough for most apps. Passport is a full OAuth2 server, needed only if other companies' apps must log in through your system.