Laravel & Backend8 min read

Building RESTful APIs with Laravel Sanctum Authentication

Md Shahed Alam
Md Shahed Alam
April 2, 2025
Building RESTful APIs with Laravel Sanctum Authentication

If you have ever tried to set up JWT authentication for a Laravel API, you know it can be more complicated than it should be. Sanctum is Laravel's official solution — and it is much simpler.

What Sanctum gives you

Sanctum handles two things: API token authentication for mobile apps and SPAs, and session authentication for browser-based applications. For most projects, you only need one of these.

Installation

composer require laravel/sanctum
php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"
php artisan migrate

Add the HasApiTokens trait to your User model:

use LaravelSanctumHasApiTokens;

class User extends Authenticatable {
    use HasApiTokens, HasFactory, Notifiable;
}

Creating tokens

When a user logs in, create a token and return it:

public function login(Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (!Auth::attempt($request->only('email', 'password'))) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $token = $request->user()->createToken('api-token')->plainTextToken;

    return response()->json(['token' => $token]);
}

Protecting routes

Add the auth:sanctum middleware to routes you want to protect:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
});

Token abilities

Sanctum lets you assign abilities to tokens. This lets you build a permission system where different tokens have different access levels:

$token = $user->createToken('admin-token', ['create', 'update', 'delete'])->plainTextToken;

Revoking tokens

Log out by deleting the current token:

$request->user()->currentAccessToken()->delete();

Or revoke all tokens at once:

$request->user()->tokens()->delete();

Sanctum is production-ready, well-documented, and maintained by the Laravel team. For most API projects, it is exactly what you need.

LaravelBackend

Ready to build something great?

Let's talk about your project. We will give you honest advice, a clear plan, and a fair price. No pressure, no sales pitch.