DEV Community

Cover image for Laravel Sanctum API Authentication: Step-by-Step Guide for Beginners
Pial Mahmud
Pial Mahmud

Posted on Edited on

Laravel Sanctum API Authentication: Step-by-Step Guide for Beginners

Introduction

Laravel Sanctum is a lightweight package for API token authentication. If you are building a Vue, React, or mobile app that needs to log in to a Laravel backend, Sanctum makes it simple.

In this guide, you will learn how to:

  • Build registration and login APIs;
  • Generate access tokens
  • Protect routes with authentication;
  • Delete the token on logout

Requirements: PHP 8.2+, Composer, and basic Laravel knowledge.

Step 1: Create a Laravel Project

bash
composer create-project laravel/laravel sanctum-auth
cd sanctum-auth
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Sanctum

In Laravel 11 and 12, one command sets up API scaffolding:

bash
php artisan install:api
Enter fullscreen mode Exit fullscreen mode

This installs Sanctum, creates routes/api.php, and publishes the personal access tokens migration.

Configure your database in .env (SQLite or MySQL), then run:

bash
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 3: Add the Trait to the User Model

Open app/Models/User.php and add the HasApiTokens trait:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

The 'password' => 'hashed' cast hashes passwords automatically, so you don’t need Hash::make().

Step 4: Create the Controller

bash
php artisan make:controller AuthController
Enter fullscreen mode Exit fullscreen mode

Step 5: Write the AuthController

Open app/Http/Controllers/AuthController.php and replace its contents:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user = User::create($data);

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

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

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

        $user = User::where('email', $data['email'])->first();

        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

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

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

    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Logged out successfully.']);
    }
}
Enter fullscreen mode Exit fullscreen mode

What each method does:

register validates input, creates the user, and returns a token. The confirmed rule expects a password_confirmation field. login checks the credentials and returns a new token. logout deletes only the token used in the current request.

**Step 6: Define the Routes

Open routes/api.php:

<?php

use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

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

    Route::post('/logout', [AuthController::class, 'logout']);
});
Enter fullscreen mode Exit fullscreen mode

Routes inside the auth:sanctum group require a valid token. Anyone else gets a 401 Unauthenticated response.

Step 7: Run the Server

bash
php artisan serve
Enter fullscreen mode Exit fullscreen mode

Your API is now available at

Step 8: Test the API with Postman

Start the server if it is not running:

bash
php artisan serve
Enter fullscreen mode Exit fullscreen mode

Important: in every request, add this header. Without it, Laravel may redirect to a web login page instead of returning JSON errors.
Accept: application/json

8.1 Register

Method: POST
URL: http://127.0.0.1:8000/api/register
Body → raw → JSON:
json
{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123"
}
Enter fullscreen mode Exit fullscreen mode

Expected response (201 Created):

json
{
    "user": {
        "name": "John Doe",
        "email": "john@example.com",
        "id": 1
    },
    "token": "1|AbCdEf123456..."
}
Enter fullscreen mode Exit fullscreen mode

Copy the token value. You will need it for the next requests.

8.2 Login

Method: POST
URL: http://127.0.0.1:8000/api/login
Body → raw → JSON:
json
{
    "email": "john@example.com",
    "password": "password123"
}

Enter fullscreen mode Exit fullscreen mode

Expected response (200 OK): the user and a new token.

Wrong password gives 422 with the message The provided credentials are incorrect.

8.3 Access a Protected Route

Method: GET
URL: http://127.0.0.1:8000/api/user
Headers:
Accept: application/json
Authorization: Bearer 1|AbCdEf123456...
Enter fullscreen mode Exit fullscreen mode

In Postman, you can also use the Authorization tab, choose Bearer Token, and paste the token.

Expected response: the logged-in user’s data.Try the same request without the token. You should get:

json
{
    "message": "Unauthenticated."
}

Enter fullscreen mode Exit fullscreen mode

8.4 Logout

Method: POST
URL: http://127.0.0.1:8000/api/logout
Headers: same Accept and Authorization headers as above

Enter fullscreen mode Exit fullscreen mode

Expected response:

json
{
    "message": "Logged out successfully."
}
Enter fullscreen mode Exit fullscreen mode

Now call GET /api/user again with the same token. It should return 401, which confirms the token was deleted.

Common Errors and Fixes

1. 401 Unauthenticated

Check these in order:

The header must be exactly Authorization: Bearer YOUR_TOKEN. Don’t forget the word Bearer and the space after it.
Copy the full token, including the number and | at the start (for example 1|AbCd...).

The token may have been deleted by logout. Log in again to get a new one.The route must be inside the auth:sanctum middleware group.

2. Route [login] not defined

This happens when you forget the Accept: application/json header. Laravel tries to redirect an unauthenticated request to a web login page, which does not exist in an API-only app. Add the header and the error becomes a proper JSON 401.

3. 422 The password field confirmation does not match

The confirmed validation rule needs a field named password_confirmation with the same value as password. Add it to your request body.

4. Call to undefined method createToken()

You forgot the HasApiTokens trait on the User model. Add' use HasApiTokens; ' inside the class, and import' Laravel\Sanctum\HasApiTokens'.

5. SQLSTATE: no such table: personal_access_tokens

The migration has not run. Run:

bash
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

6. CORS error in the browser

This appears when your Vue or React app (for example, localhost:5173) calls the API on another origin.

Publish the CORS config:

bash
php artisan config:publish cors
Enter fullscreen mode Exit fullscreen mode

Then edit config/cors.php and allow your frontend origin:

'paths' => ['api/*'],
'allowed_origins' => ['http://localhost:5173'],
'allowed_headers' => ['*'],
'allowed_methods' => ['*'],
Enter fullscreen mode Exit fullscreen mode

Clear the config cache after changes:

bash
php artisan config:clear
Conclusion
Enter fullscreen mode Exit fullscreen mode

You now have a working token-based authentication API with:

Register and login endpoints that return a token A protected route using auth:sanctum; and logout that deletes the current token.

This token approach works well for mobile apps and third-party clients. For a Vue SPA on the same top-level domain, Sanctum also supports cookie-based SPA authentication, which I will cover in the next post: Vue 3 + Laravel Sanctum login with Pinia.

If this guide helped, leave a ❤️ and follow for more Laravel and Vue tutorials.

Top comments (0)