Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Blog · Laravel

Laravel API Authentication with Sanctum: Step-by-Step

Laravel API Authentication with Sanctum: Step-by-Step
Advertisement

Laravel Sanctum is the right choice when a JavaScript frontend (Vue, React, Next.js) or a mobile app needs to authenticate against your Laravel API — it's far lighter than a full OAuth2 server like Passport, and covers 90% of real-world API auth needs.

Two Modes: SPA and Token

Sanctum actually solves two different problems. For a first-party SPA served from the same top-level domain, it uses Laravel's normal session cookies — no tokens involved at all. For mobile apps or third-party clients, it issues API tokens instead. This guide covers the token flow, since that's what most Next.js/React frontends on a separate domain need.

Installing Sanctum

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Then add the trait to your User model:

class User extends Authenticatable
{
    use HasApiTokens;
}

Issuing a Token on Login

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)) {
        return response()->json(['message' => 'Invalid credentials'], 422);
    }

    return response()->json([
        'token' => $user->createToken('api-token')->plainTextToken,
    ]);
});

The client stores this token (typically in memory or a secure cookie, never plain localStorage if you can avoid it) and sends it on every request:

Authorization: Bearer {token}

Protecting Routes

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', fn (Request $r) => $r->user());
    Route::apiResource('posts', PostController::class);
});

Revoking Tokens on Logout

Route::post('/logout', function (Request $request) {
    $request->user()->currentAccessToken()->delete();
    return response()->noContent();
})->middleware('auth:sanctum');

Token Abilities (Scopes)

Sanctum tokens can carry specific abilities, so a token issued to a read-only integration can't accidentally delete data:

$user->createToken('mobile-app', ['posts:read', 'posts:write']);

Check them with $request->user()->tokenCan('posts:write') inside a controller before allowing a mutating action.

That's a complete, production-reasonable token auth flow — no third-party auth server required.

Laravel for Beginners: Setting Up Your First Project

Laravel for Beginners: Setting Up Your First Project

A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.

Building a REST API with Laravel: A Complete Guide

Building a REST API with Laravel: A Complete Guide

API routes, resources, Form Request validation, correct status codes, and Sanctum auth — a real, production-reasonable Laravel API.

Laravel Eloquent Relationships Explained with Real Examples

Laravel Eloquent Relationships Explained with Real Examples

One-to-many, many-to-many, polymorphic, and the N+1 query trap that catches almost every Laravel developer at least once.

Esc