6 min read

Laravel Sanctum 101: A Developer’s Guide to Easy Authentication

Interested in generating passive income? Join our partnership program and receive a commission on each new client referral. Learn more.

Laravel Sanctum is an authentication system for SPAs (Single Page Applications), mobile applications, and basic token-based APIs. It is designed to be simple and developer-friendly, which makes it a preferred choice for handling API authentication in Laravel applications.

We will take a closer look at Laravel Sanctum and explore its features, setup, and usage in depth. So let’s get into it.

Key Features of Laravel Sanctum

Here are some of the standout features of Laravel Sanctum that highlight why you should consider using this tool to simplify authentication.

Token-Based Authentication

Sanctum allows users to issue API tokens without the complexity of OAuth. These tokens can be scoped, restricting the actions they can perform. This is particularly useful for managing API access for different parts of your application or for external services.

SPA Authentication

For SPAs, Sanctum uses cookie-based session authentication, which allows your JavaScript front end to authenticate using the same Laravel session cookies. This approach provides a seamless and secure authentication mechanism for SPAs.

CSRF Protection

Sanctum offers robust CSRF protection for your application. When using Sanctum, your API requests are protected against CSRF attacks, ensuring the security of your application.

How to Install Laravel Sanctum?

Setting up Sanctum is quite simple in Laravel 11, with this simple Artisan command:

php artisan install:api

Using Sanctum for API Token Authentication

To issue a token to a user, first, you need to update the User model:

class User extends Authenticatable
      use HasApiTokens, HasFactory, Notifiable;

Creating token:

$token = $request->user()->createToken($request->token_name);

return ['token' => $token->plainTextToken];

Revoking tokens:

// Revoke all tokens...
// Revoke the token that was used to authenticate the current request...
// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();

Token Scopes

Tokens can have scopes that define their permissions. When creating a token, you can specify the scopes:

$token = $user->createToken('token-name', ['view-posts', 'create-posts'])

You can then check the token’s scopes in your routes or controllers:

if ($user->tokenCan('create-posts')) {
   // ...

Protecting Routes with Laravel Sanctum

Sanctum provides powerful middleware to check incoming requests if it is authenticated and have the token ability:

use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
->withMiddleware(function (Middleware $middleware) {
        'abilities' => CheckAbilities::class,
        'ability' => CheckForAnyAbility::class,

To protect routes, you should use the auth:sanctum and ability (abilities) middleware:

Route::middleware(['auth:sanctum', 'abilities: create-post'])
    ->post('/posts/create', function (Request $request) {

The difference between ability and abilities is quite simple:

  • ability middleware checks if the token has at least one ability
  • abilities middleware checks if the token has every listed ability

SPA Authentication

For SPAs, you need to set up session-based authentication. Typically, you will have a login route that your SPA will use to authenticate:

Route::post('/login', function (Request $request) {
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        return response()->json(['message' => 'Logged in successfully']);

    return response()->json(['message' => 'Invalid credentials'], 401);

After logging in, your SPA can make authenticated requests using the session cookie.

Handling in frontend

When issuing a request for the sanctum route, first, you need to make a request on /sanctum/csrf-cookie to init CSRF protection:

axios.get('/sanctum/csrf-cookie').then(response => {
    axios.post('/login', {
        email: 'user@example.com',
        password: 'password'
    }).then(response => {
        // Handle successful authentication
    }).catch(error => {
        // Handle authentication failure

Final Thoughts on Laravel Sanctum

Laravel Sanctum provides a simple yet powerful solution for API token management and SPA authentication. Its ease of use, combined with Laravel’s robust features, makes it an excellent choice for developers looking to implement secure authentication mechanisms. It doesn’t matter whether you’re building an API, a mobile app, or a SPA; Laravel Sanctum offers the flexibility and simplicity you need to manage authentication effectively.

Meet the authors

We are a 200+ people agency and provide product design, software development, and creative growth marketing services to companies ranging from fresh startups to established enterprises. Our work has earned us 100+ international awards, partnerships with Laravel, Vue, Meta, and Google, and the title of Georgia’s agency of the year in 2019 and 2021.

Contact us