Laravel Sanctum for PHP: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Laravel Sanctum for PHP: Complete Guide to API Tokens and SPA Authentication

\n\n

1. What It Is and Why You Need It

\n\n

Laravel Sanctum is a lightweight authentication library for the PHP framework Laravel, designed for managing API tokens and single-page applications (SPA). Developed by Taylor Otwell and the Laravel team, Sanctum provides a simple yet powerful way to protect API routes, allowing developers to quickly implement authentication without the complex setup typical of heavier solutions like Passport (OAuth2).

\n\n

Sanctum's main task is to solve two key problems of modern web development: authentication for SPAs (Single Page Applications) running on the same domain as the backend, and issuing API tokens for mobile applications or third-party services. Unlike Passport, Sanctum does not use the full OAuth2 protocol, making it an ideal choice for projects that do not require a complex access delegation system. It uses Laravel sessions for SPA authentication and simple HMAC-based tokens for the API.

\n\n

The library is included in the standard Laravel 8 and higher distribution, making it available "out of the box." Sanctum is especially useful for startups, small teams, and projects where development speed and minimal dependencies are important. It automatically manages token expiration, supports "abilities" for fine-grained access control, and integrates easily with Laravel Fortify, Breeze, or Jetstream.

\n\n

2. Installation

\n\n

Laravel Sanctum is installed via Composer, the standard package manager for PHP. Make sure you have PHP 8.0 or higher and Laravel 8.x/9.x/10.x/11.x installed.

\n\n

The exact command for installation:

\n
composer require laravel/sanctum
\n\n

After installation, you need to publish the configuration file and database migrations:

\n
php artisan vendor:publish --provider="Laravel\\Sanctum\\SanctumServiceProvider"
\n\n

Then run the migrations to create the personal_access_tokens table:

\n
php artisan migrate
\n\n

For SPA authentication, you additionally need to add the EnsureFrontendRequestsAreStateful middleware to the HTTP kernel (file app/Http/Kernel.php):

\n
'api' => [\n    \\Laravel\\Sanctum\\Http\\Middleware\\EnsureFrontendRequestsAreStateful::class,\n    'throttle:api',\n    \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n],
\n\n

Also, in the .env file, specify your SPA domain:

\n
SANCTUM_STATEFUL_DOMAINS=localhost:8080
\n\n

3. Quick Start — Minimal Working Example

\n\n

Let's look at a minimal example of issuing an API token and protecting a route.

\n\n

Step 1: User Model

\n

In the App\\Models\\User model, use the HasApiTokens trait:

\n
\n\n

Step 2: Route for Issuing a Token

\n

Create a route in routes/api.php:

\n
validate([\n        'email' => 'required|email',\n        'password' => 'required',\n    ]);\n\n    if (auth()->attempt($credentials)) {\n        $user = auth()->user();\n        $token = $user->createToken('api-token')->plainTextToken;\n        \n        ret                    

Recommendations