Skip to main content

Web frameworks · Intermediate · 28 min

Build a token-authenticated JSON API with Laravel Sanctum

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · bash · PHP 8.5 · Laravel 13.43 · Sanctum 4.5 · SQLite · checked on php:8.5-cli

You will build a Laravel 13 JSON API for a small shop's mobile app, with Sanctum tokens that carry abilities, protected and paginated product routes, rate limits on sign-in, and feature tests for the token flows.

On this page

Laravel Sanctum gives a Laravel app simple API tokens. A user signs in once, the app hands back a long random token, and every later request sends it in an Authorization: Bearer header. Sanctum stores only a SHA-256 hash of each token in the database, so a leaked database does not leak working tokens. Each token can carry abilities, short strings such as products:read, so a token you give a stock-checking app cannot change prices.

You will build the API behind a small shop's mobile app: a sign-in endpoint that issues tokens, a paginated product list, an endpoint that adds products, and one that revokes the current token. Then you will rate limit sign-in, call everything with curl, and cover the token flows with feature tests. All of it runs on your own machine with SQLite, so there is no database server to set up.

The project lives in ~/sanctum-demo, which you delete at the end. If you have not installed PHP 8.5 and Composer yet, follow Install Laravel 13 on Ubuntu 26.04 first.

Step 1 · Create the project and install Sanctum

Create a Laravel 13 project. The ^13.0 constraint keeps you on Laravel 13 while allowing its updates:

Bash
mkdir -p ~/sanctum-demo
cd ~/sanctum-demo
composer create-project laravel/laravel:^13.0 shop-api --no-interaction
cd shop-api
php artisan --version

A new Laravel project has no API routes. php artisan install:api adds them: it installs the laravel/sanctum package with Composer, publishes the migration for the personal_access_tokens table, creates routes/api.php and registers that file in bootstrap/app.php under the /api prefix. The flag skips its question about running migrations, because you will run them once your own tables are ready:

Bash
php artisan install:api --without-migration-prompt

Check it worked

php artisan --version printed Laravel Framework 13. and a release number. Confirm Sanctum is installed and the new pieces are in place:

Bash
composer show laravel/sanctum | grep -E '^versions'
ls routes
ls database/migrations | grep personal_access_tokens

The first line reads versions : * v4. followed by a patch release, routes now lists api.php next to web.php and console.php, and one migration file ends in _create_personal_access_tokens_table.php.

Step 2 · Let users hold tokens

Sanctum needs the HasApiTokens trait on the model that owns tokens. It adds createToken(), tokens(), tokenCan() and currentAccessToken() to every user. Replace app/Models/User.php with this version, which is the starter model plus that one trait:

Bash
cat > app/Models/User.php <<'PHP'
<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}
PHP

If you have already changed your own User model, add use Laravel\Sanctum\HasApiTokens; at the top and HasApiTokens to its use line instead of replacing the file.

Check it worked

Ask PHP whether the trait is now part of the class:

Bash
php artisan tinker --execute 'var_dump(in_array(Laravel\Sanctum\HasApiTokens::class, class_uses(App\Models\User::class)));'

The output is bool(true).

Step 3 · Add products, a resource and demo data

The app lists products. Create the model and an API resource with Artisan (--no-interaction skips the question about extra files), then write the migration yourself. A resource is a class that decides what JSON a model becomes, so the shape your mobile app depends on does not change every time you add a database column:

Bash
php artisan make:model Product --no-interaction
php artisan make:resource ProductResource --no-interaction

Replace the generated model. Prices are stored as whole numbers in the currency's smallest unit (cents, kobo, shillings' cents), because floating-point numbers cannot hold most decimal amounts exactly:

Bash
cat > app/Models/Product.php <<'PHP'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['name', 'sku', 'price_minor', 'currency'])]
class Product extends Model
{
    protected function casts(): array
    {
        return ['price_minor' => 'integer'];
    }
}
PHP

Write the migration with a fixed file name:

Bash
cat > database/migrations/2026_11_19_000000_create_products_table.php <<'PHP'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 120);
            $table->string('sku', 40)->unique();
            $table->unsignedBigInteger('price_minor');
            $table->char('currency', 3);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
PHP

Replace the resource. The price becomes a small object with an amount and a currency code, and the timestamp is ISO 8601, which every mobile platform can parse:

Bash
cat > app/Http/Resources/ProductResource.php <<'PHP'
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'sku' => $this->sku,
            'price' => [
                'amount' => $this->price_minor,
                'currency' => $this->currency,
            ],
            'created_at' => $this->created_at?->toIso8601String(),
        ];
    }
}
PHP

Now a seeder for one user and 25 products. It reads the user's password from an environment variable, so the password never sits in the code or in your shell history:

Bash
cat > database/seeders/DemoSeeder.php <<'PHP'
<?php

namespace Database\Seeders;

use App\Models\Product;
use App\Models\User;
use Illuminate\Database\Seeder;
use RuntimeException;

class DemoSeeder extends Seeder
{
    public function run(): void
    {
        $password = env('DEMO_PASSWORD');

        if (! is_string($password) || strlen($password) < 12) {
            throw new RuntimeException('Set DEMO_PASSWORD to at least 12 characters first.');
        }

        User::updateOrCreate(
            ['email' => 'ada@example.com'],
            ['name' => 'Ada', 'password' => $password],
        );

        $names = ['Maize flour 5 kg', 'Rice 10 kg', 'Palm oil 1 L', 'Beans 2 kg', 'Sugar 1 kg'];

        foreach (range(1, 25) as $i) {
            Product::updateOrCreate(
                ['sku' => sprintf('SKU-%03d', $i)],
                [
                    'name' => $names[$i % 5],
                    'price_minor' => 150000 + $i * 2500,
                    'currency' => 'NGN',
                ],
            );
        }
    }
}
PHP

Choose a password for the demo user, at least 12 characters. The prompt does not echo what you type. The commands in this tutorial are written for bash, the default shell on Ubuntu:

Bash
read -rsp 'Password for ada@example.com: ' DEMO_PASSWORD; echo
export DEMO_PASSWORD

On macOS the default shell is zsh, where read -p means something else. Use this form there instead:

Bash
read -rs 'DEMO_PASSWORD?Password for ada@example.com: '; echo
export DEMO_PASSWORD

Run the migrations (the Sanctum table and yours) and the seeder:

Bash
php artisan migrate --no-interaction
php artisan db:seed --class=DemoSeeder --no-interaction

Check it worked

migrate lists the two new migrations as DONE. Count the rows:

Bash
php artisan tinker --execute 'echo App\Models\User::count(), " user, ", App\Models\Product::count(), " products", PHP_EOL;'

The output is 1 user, 25 products. If the seeder stopped with Set DEMO_PASSWORD to at least 12 characters first., run the read and export lines again in the same terminal, then the seeder.

Step 4 · Write the controllers, rate limits and routes

The token controller has two actions. store checks an email and password and issues a token that expires in 30 days, with the abilities the client asked for from an allowed list. destroy deletes the token that made the current request, which is how a mobile app signs out:

Bash
mkdir -p app/Http/Controllers/Api
cat > app/Http/Controllers/Api/TokenController.php <<'PHP'
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class TokenController extends Controller
{
    /** Abilities a client may ask for. */
    public const ABILITIES = ['products:read', 'products:write'];

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
            'device_name' => ['required', 'string', 'max:100'],
            'abilities' => ['sometimes', 'array', 'min:1'],
            'abilities.*' => ['string', Rule::in(self::ABILITIES)],
        ]);

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

        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages([
                'email' => 'These credentials do not match our records.',
            ]);
        }

        $abilities = $data['abilities'] ?? ['products:read'];
        $token = $user->createToken($data['device_name'], $abilities, now()->addDays(30));

        return response()->json([
            'token' => $token->plainTextToken,
            'abilities' => $abilities,
            'expires_at' => $token->accessToken->expires_at->toIso8601String(),
        ], 201);
    }

    public function destroy(Request $request): Response
    {
        $request->user()->currentAccessToken()->delete();

        return response()->noContent();
    }
}
PHP

In a real shop, decide abilities from the user's role rather than letting any signed-in user ask for products:write. The allowed list here keeps the example short.

The product controller lists products a page at a time, shows one, and creates one. per_page is limited to between 1 and 50, so no client can ask for the whole table in one response. Small pages also matter to people on prepaid mobile data, who pay for every kilobyte your API sends:

Bash
cat > app/Http/Controllers/Api/ProductController.php <<'PHP'
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class ProductController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $perPage = min(max((int) $request->query('per_page', 10), 1), 50);

        $products = Product::query()
            ->orderBy('id')
            ->paginate($perPage)
            ->withQueryString();

        return ProductResource::collection($products);
    }

    public function show(Product $product): ProductResource
    {
        return new ProductResource($product);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'sku' => ['required', 'string', 'max:40', 'unique:products,sku'],
            'price_minor' => ['required', 'integer', 'min:0'],
            'currency' => ['required', 'string', 'size:3', 'alpha'],
        ]);

        $data['currency'] = strtoupper($data['currency']);
        $product = Product::create($data);

        return (new ProductResource($product))->response()->setStatusCode(201);
    }
}
PHP

Rate limiters are named rules you attach to routes with the throttle middleware. Define two in app/Providers/AppServiceProvider.php. api allows 60 requests a minute per signed-in user. tokens allows 5 sign-in attempts a minute for each email address from each IP address, which slows down password guessing. The starter file has empty methods, so replace it; if you have already put code in it, add the two RateLimiter::for calls to your own boot method instead:

Bash
cat > app/Providers/AppServiceProvider.php <<'PHP'
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        RateLimiter::for('tokens', function (Request $request) {
            $email = strtolower((string) $request->input('email'));

            return Limit::perMinute(5)->by($email.'|'.$request->ip());
        });
    }
}
PHP

Finally, replace routes/api.php. auth:sanctum rejects any request without a valid, unexpired token. Sanctum's CheckAbilities middleware then checks that the token carries the ability named after the colon:

Bash
cat > routes/api.php <<'PHP'
<?php

use App\Http\Controllers\Api\ProductController;
use App\Http\Controllers\Api\TokenController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;

Route::post('/tokens', [TokenController::class, 'store'])
    ->middleware('throttle:tokens');

Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::get('/user', fn (Request $request) => $request->user());
    Route::delete('/tokens/current', [TokenController::class, 'destroy']);

    Route::get('/products', [ProductController::class, 'index'])
        ->middleware(CheckAbilities::class.':products:read');
    Route::get('/products/{product}', [ProductController::class, 'show'])
        ->middleware(CheckAbilities::class.':products:read');
    Route::post('/products', [ProductController::class, 'store'])
        ->middleware(CheckAbilities::class.':products:write');
});
PHP

Check it worked

List the API routes:

Bash
php artisan route:list --path=api

The table shows six routes, all starting with api/: POST api/tokens, GET|HEAD api/user, DELETE api/tokens/current, GET|HEAD api/products, GET|HEAD api/products/{product} and POST api/products, with the controller action for each. If the command reports a PHP error instead, it names the file and line to fix.

Step 5 · Start the server and issue tokens

Start the development server in your first terminal and leave it running:

Bash
cd ~/sanctum-demo/shop-api
php artisan serve

Open a second terminal and work there from here on. It is a new shell, so it does not have DEMO_PASSWORD. Set it again, typing the same password you gave the seeder (in zsh, use the read -rs 'DEMO_PASSWORD?...' form from earlier):

Bash
read -rsp 'Password for ada@example.com: ' DEMO_PASSWORD; echo
export DEMO_PASSWORD

Make a folder for the client side, outside the project so nothing in it is ever committed.

The sign-in request body holds the password, so build it with PHP from the environment variable, and create the file readable only by you. umask 077 inside the brackets applies only to that one command:

Bash
mkdir -p ~/sanctum-demo/client
cd ~/sanctum-demo/client
(umask 077; php -r 'echo json_encode(["email" => "ada@example.com", "password" => getenv("DEMO_PASSWORD"), "device_name" => "ada-phone", "abilities" => ["products:read"]]);' > login-read.json)
(umask 077; php -r 'echo json_encode(["email" => "ada@example.com", "password" => getenv("DEMO_PASSWORD"), "device_name" => "ada-laptop", "abilities" => ["products:read", "products:write"]]);' > login-write.json)

Every request sends Accept: application/json. That header tells Laravel the caller wants JSON, so errors come back as JSON with the right status code rather than as an HTML page or a redirect. Your mobile app must send it too. Ask for a read-only token and a read-write token:

Bash
(umask 077; curl -s -o read-token.json -w '%{http_code}\n' -X POST http://127.0.0.1:8000/api/tokens -H 'Accept: application/json' -H 'Content-Type: application/json' --data-binary @login-read.json)
(umask 077; curl -s -o write-token.json -w '%{http_code}\n' -X POST http://127.0.0.1:8000/api/tokens -H 'Accept: application/json' -H 'Content-Type: application/json' --data-binary @login-write.json)

Each prints 201. If either prints 422, the sign-in was refused: almost always DEMO_PASSWORD is not set in this terminal, or holds a different password from the one you seeded, so the login file carries the wrong value. Run php -r 'var_dump(getenv("DEMO_PASSWORD") !== false);'; if it prints bool(false), set the variable as above, then rebuild both login files and repeat the two requests.

Turn each token into a header file, so the token is not typed into later commands, where it would show in your shell history and in the process list:

Bash
(umask 077; php -r 'echo "Authorization: Bearer ", json_decode(file_get_contents("read-token.json"))->token, "\n";' > read-auth.txt)
(umask 077; php -r 'echo "Authorization: Bearer ", json_decode(file_get_contents("write-token.json"))->token, "\n";' > write-auth.txt)
ls -l

Treat these files like passwords. Anyone with a token can act as Ada until it expires or is revoked. A mobile app keeps its token in the platform's protected storage (the Android Keystore or the iOS Keychain), never in plain preferences or logs.

Check it worked

ls -l shows six files, each starting with -rw-------. Look at the read-only response, which does not include anything secret beyond the token itself:

Bash
php -r '$r = json_decode(file_get_contents("read-token.json")); echo implode(",", $r->abilities), " until ", $r->expires_at, PHP_EOL;'

It prints products:read until and a date 30 days from now. A token looks like 1| followed by a long random string: the number is the token's row ID, and only a hash of the part after the bar is stored in the personal_access_tokens table.

Step 6 · Call the API with each token

First, prove the routes are closed without a token:

Bash
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/api/products -H 'Accept: application/json'

It prints {"message":"Unauthenticated."} and 401. Now ask for the first page of five products with the read-only token. A small PHP one-liner pretty-prints the JSON:

Bash
curl -s 'http://127.0.0.1:8000/api/products?per_page=5' -H 'Accept: application/json' -H @read-auth.txt | php -r 'echo json_encode(json_decode(stream_get_contents(STDIN)), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;'

The response has three parts. data holds five products shaped by ProductResource, the first with "sku": "SKU-001" and "price": {"amount": 152500, "currency": "NGN"}. links holds first, last, prev and next URLs; next ends in ?per_page=5&page=2, because withQueryString() keeps the page size in every link. meta holds current_page, last_page (5), per_page, total (25) and a links array for building numbered page buttons. A mobile app follows links.next until it is null.

Try to add a product with the read-only token:

Bash
(umask 077; curl -s -o forbidden.json -w '%{http_code}\n' -X POST http://127.0.0.1:8000/api/products -H 'Accept: application/json' -H 'Content-Type: application/json' -H @read-auth.txt --data '{"name":"Garri 2 kg","sku":"GARRI-002","price_minor":250000,"currency":"ngn"}')
php -r 'echo json_decode(file_get_contents("forbidden.json"))->message, PHP_EOL;'

The token is valid, but it lacks products:write, so the status is 403 and the message is Invalid ability provided.. The full body in forbidden.json holds more than the message: the project's .env sets APP_DEBUG=true for local development, so Laravel adds exception, file, line and a long trace to this error. A production server must set APP_DEBUG=false, or those details about your code reach every client. Send the same request with the read-write token:

Bash
curl -s -w '\n%{http_code}\n' -X POST http://127.0.0.1:8000/api/products -H 'Accept: application/json' -H 'Content-Type: application/json' -H @write-auth.txt --data '{"name":"Garri 2 kg","sku":"GARRI-002","price_minor":250000,"currency":"ngn"}'

Check it worked

The last command prints the new product inside {"data": ...} with "id":26, "currency":"NGN" (the controller upper-cased it) and status 201. Send exactly the same request again: the answer is 422 with an errors object saying The sku has already been taken., because validation failures from an API also come back as JSON.

Step 7 · Hit the sign-in rate limit and revoke a token

Make seven sign-in attempts in a row for an address with the wrong password, and print only the status codes:

Bash
for i in 1 2 3 4 5 6 7; do
  curl -s -o /dev/null -w '%{http_code} ' -X POST http://127.0.0.1:8000/api/tokens -H 'Accept: application/json' -H 'Content-Type: application/json' --data '{"email":"nobody@example.com","password":"not-the-password","device_name":"guess"}'
done
echo

The output is 422 422 422 422 422 429 429. The first five attempts reach the controller and fail validation. From the sixth, the tokens limiter answers 429 Too Many Requests before your code runs. Look at the headers of one more attempt:

Bash
curl -s -o /dev/null -D - -X POST http://127.0.0.1:8000/api/tokens -H 'Accept: application/json' -H 'Content-Type: application/json' --data '{"email":"nobody@example.com","password":"not-the-password","device_name":"guess"}' | grep -i -E '^(retry-after|x-ratelimit-limit|x-ratelimit-remaining):'

You see X-RateLimit-Limit: 5, X-RateLimit-Remaining: 0 and Retry-After: with the number of seconds until the window resets. A well-behaved client waits that long before trying again. Ada's own sign-in is unaffected, because the limiter counts each email address separately. If you run the loop again within a minute, every attempt is 429.

Now sign the phone out. The read-only token deletes itself:

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://127.0.0.1:8000/api/tokens/current -H 'Accept: application/json' -H @read-auth.txt

Check it worked

The delete printed 204. Use the same token again, then the read-write token:

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/user -H 'Accept: application/json' -H @read-auth.txt
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/user -H 'Accept: application/json' -H @write-auth.txt

The revoked token gets 401, and the laptop's token still gets 200: revoking one device leaves the others signed in. To sign a user out everywhere, delete all their tokens with $user->tokens()->delete().

Step 8 · Test the token flows

curl checks are good for exploring; tests keep the API working as it changes. Laravel's JSON test helpers send requests through the app in memory, with no server, and the starter phpunit.xml points tests at an in-memory SQLite database, so they never touch your demo data. Sanctum::actingAs signs a user in with a token that has exactly the abilities you list. Go back to the project folder and add a test file:

Bash
cd ~/sanctum-demo/shop-api
cat > tests/Feature/ProductApiTest.php <<'PHP'
<?php

namespace Tests\Feature;

use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class ProductApiTest extends TestCase
{
    use RefreshDatabase;

    private function makeProducts(int $count): void
    {
        foreach (range(1, $count) as $i) {
            Product::create([
                'name' => "Test product {$i}",
                'sku' => sprintf('TEST-%03d', $i),
                'price_minor' => 1000 * $i,
                'currency' => 'KES',
            ]);
        }
    }

    public function test_a_user_can_get_a_token_and_use_it(): void
    {
        User::factory()->create(['email' => 'tester@example.com', 'password' => 'a-long-test-password']);
        $this->makeProducts(1);

        $token = $this->postJson('/api/tokens', [
            'email' => 'tester@example.com',
            'password' => 'a-long-test-password',
            'device_name' => 'phpunit',
        ])->assertCreated()
            ->assertJsonPath('abilities', ['products:read'])
            ->json('token');

        $this->withToken($token)
            ->getJson('/api/products')
            ->assertOk()
            ->assertJsonPath('data.0.sku', 'TEST-001');
    }

    public function test_a_wrong_password_gets_no_token(): void
    {
        User::factory()->create(['email' => 'tester@example.com', 'password' => 'a-long-test-password']);

        $this->postJson('/api/tokens', [
            'email' => 'tester@example.com',
            'password' => 'wrong-password',
            'device_name' => 'phpunit',
        ])->assertUnprocessable()->assertJsonValidationErrors('email');

        $this->assertDatabaseCount('personal_access_tokens', 0);
    }

    public function test_products_need_a_token(): void
    {
        $this->getJson('/api/products')->assertUnauthorized();
    }

    public function test_a_read_only_token_cannot_create_products(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['products:read']);

        $this->postJson('/api/products', [
            'name' => 'Sukuma wiki bunch',
            'sku' => 'SUKUMA-01',
            'price_minor' => 3000,
            'currency' => 'kes',
        ])->assertForbidden();

        $this->assertDatabaseCount('products', 0);
    }

    public function test_a_write_token_creates_a_product(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['products:write']);

        $this->postJson('/api/products', [
            'name' => 'Sukuma wiki bunch',
            'sku' => 'SUKUMA-01',
            'price_minor' => 3000,
            'currency' => 'kes',
        ])->assertCreated()
            ->assertJsonPath('data.price.amount', 3000)
            ->assertJsonPath('data.price.currency', 'KES');
    }

    public function test_products_are_paginated(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['products:read']);
        $this->makeProducts(12);

        $this->getJson('/api/products?per_page=5&page=3')
            ->assertOk()
            ->assertJsonCount(2, 'data')
            ->assertJsonPath('meta.total', 12)
            ->assertJsonPath('meta.last_page', 3)
            ->assertJsonPath('links.next', null);
    }
}
PHP
php artisan test

Check it worked

Each test is listed with PASS: the six in ProductApiTest and the two example tests that came with the project. The run ends with a line like Tests: 8 passed followed by the assertion count and a duration. To see a test catch a real mistake, change products:write to products:read on the POST /products route in routes/api.php and run php artisan test again: two tests fail. test_a_read_only_token_cannot_create_products gets 201 instead of 403, because a read token is now enough to create a product, and test_a_write_token_creates_a_product gets 403 instead of 201, because its token carries only products:write. Change it back before you go on.

Step 9 · Stop the server and clean up

Press Ctrl+C in the terminal that runs php artisan serve.

Delete the project, the client files with their tokens, and the password variable:

Bash
cd ~
rm -rf ~/sanctum-demo
unset DEMO_PASSWORD

Check it worked

ls ~/sanctum-demo reports No such file or directory. PHP and Composer stay installed for your next project.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.