Laravel has long been the go-to framework for PHP developers who want to ship production-quality APIs quickly. With Laravel 11, the team streamlined the application structure even further — fewer files, faster boot, the same expressive syntax you love.

In this tutorial, we'll build a fully authenticated REST API for a simple task manager. By the end, you'll have a working API with user registration, login, and CRUD for tasks — all secured with Sanctum tokens.

1. Project Setup

Create a fresh Laravel 11 project and install Sanctum:

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

In bootstrap/app.php, make sure API middleware is configured. Laravel 11 ships with a slim bootstrap that includes Sanctum middleware by default when you publish its config.

2. Building the Auth Endpoints

Create a dedicated API auth controller:

php artisan make:controller Api/AuthController

Add register, login, and logout methods. The key pattern is returning a Sanctum token on success:

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);
    }

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

3. Task Resource & Routes

Generate the model, migration, and resource controller in one go:

php artisan make:model Task -mrc --api

Your migration should include user_id, title, description, and completed_at. Run php artisan migrate when ready.

Resource Responses

Always use API Resources to shape your JSON — never return Eloquent models directly. This gives you control over the exact response shape and protects sensitive fields.

Pro tip: Add ->only(['id', 'title', 'completed_at']) in your resource's toArray() to strip internal fields. Your clients will thank you when you refactor the database later.

4. Testing the API

Use Laravel's built-in HTTP tests — they're faster than Postman for CI pipelines:

public function test_user_can_create_a_task(): void
{
    $user = User::factory()->create();

    $this->actingAs($user, 'sanctum')
         ->postJson('/api/tasks', ['title' => 'Write docs'])
         ->assertCreated()
         ->assertJsonPath('data.title', 'Write docs');
}

5. Deploying to Production

Before deploying, run the optimization commands and set SANCTUM_STATEFUL_DOMAINS in your .env to the domains that will use cookie-based auth.

That's it! You now have a clean, tested, production-ready Laravel 11 REST API. The full source code is available in the course resources on Everest Skills Academy.