Skip to content

3. Your first resource ​

In this step you add orders: a team places an order, for an amount in a currency, and it moves from pending to paid to shipped. By the end, the API can place, list and fetch orders, rejects invalid ones, and has tests that prove it.

An endpoint in Fusion Stack is built from a few small classes. Each does one job:

ClassIts job
ModelAn order in the database, with Laravel's Eloquent.
ResourceWhat clients see of an order.
QueryWhat clients may ask for: filters, sorts and related resources.
Form requestWhat clients may send, and what is valid.
ControllerTies them together, one method per endpoint.

Run the commands in your second terminal, in the api folder. Keep npm run dev running in the first.

The table and the model ​

Ask Laravel for the model, with -m for a migration and -f for a factory:

sh
php artisan make:model Order -mf
text
INFO Model [app/Models/Order.php] created successfully.
INFO Factory [database/factories/OrderFactory.php] created successfully.
INFO Migration [database/migrations/…_create_orders_table.php] created successfully.

A migration creates or changes a table. Its name starts with the date and time you created it, so yours differs from the one below. Replace its contents with:

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('orders', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('team_id')->constrained()->cascadeOnDelete();
            $table->string('status')->default('pending');
            $table->unsignedInteger('total_cents');
            $table->char('currency', 3);
            $table->timestamps();
        });
    }

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

Each order belongs to a team, through team_id. Amounts are stored as whole numbers in the smallest unit of the currency, such as pence for pounds: £25.00 is 2500. Decimal amounts suffer rounding errors, and whole numbers do not.

The model is how your code reads and writes orders:

php
<?php

namespace App\Models;

use Database\Factories\OrderFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @property int $id
 * @property int $team_id
 * @property string $status
 * @property int $total_cents
 * @property string $currency
 */
#[Fillable(['team_id', 'status', 'total_cents', 'currency'])]
final class Order extends Model
{
    /** @use HasFactory<OrderFactory> */
    use HasFactory;

    public const array STATUSES = ['pending', 'paid', 'shipped', 'cancelled'];

    public const array CURRENCIES = ['EUR', 'GBP', 'USD'];

    /** @var array<string, mixed> */
    protected $attributes = ['status' => 'pending'];

    /** @return BelongsTo<Team, $this> */
    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }
}

#[Fillable] lists the columns that may be set in bulk, as the controller does below. New orders are pending.

A factory makes orders with made-up values, for tests and for the examples in the API reference:

php
<?php

namespace Database\Factories;

use App\Models\Order;
use App\Models\Team;
use Illuminate\Database\Eloquent\Factories\Factory;

/** @extends Factory<Order> */
final class OrderFactory extends Factory
{
    public function definition(): array
    {
        return [
            'team_id' => Team::factory(),
            'status' => fake()->randomElement(Order::STATUSES),
            'total_cents' => fake()->numberBetween(500, 50000),
            'currency' => fake()->randomElement(Order::CURRENCIES),
        ];
    }
}

Now create the table:

sh
php artisan migrate
text
INFO Running migrations.
…_create_orders_table … DONE

What clients see ​

The resource lists the attributes and relationships of an order that clients see. Anything else on the model, such as team_id or updated_at, stays private. #[Describe] explains each one in the API reference:

php
<?php

namespace App\Http\Resources;

use FusionStack\Laravel\OpenApi\Describe;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;

#[Describe('status', 'Where the order is in fulfilment.', values: [
    'pending' => 'Placed, awaiting payment',
    'paid' => 'Paid, not yet shipped',
    'shipped' => 'Handed to the courier',
    'cancelled' => 'Cancelled before shipping',
])]
#[Describe('total_cents', 'The order total in the smallest unit of the currency, such as pence.')]
#[Describe('currency', 'An ISO 4217 currency code: EUR, GBP or USD.')]
#[Describe('created_at', 'When the order was placed.')]
#[Describe('team', 'The team that placed the order.')]
final class OrderResource extends JsonApiResource
{
    /** @var list<string> */
    public array $attributes = ['status', 'total_cents', 'currency', 'created_at'];

    /** @var list<string> */
    public array $relationships = ['team'];
}

What clients may ask for ​

The query turns the request's query string into a database query. For now it says only which fields exist and that the newest orders come first. In step 4 you let clients filter and sort.

php
<?php

namespace App\Http\Queries;

use App\Models\Order;
use FusionStack\Laravel\Query\ApiQuery;

/** @extends ApiQuery<Order> */
final class OrderQuery extends ApiQuery
{
    protected string $model = Order::class;

    protected array $fields = [
        'orders' => ['status', 'total_cents', 'currency', 'created_at', 'team'],
    ];

    protected string $defaultSort = '-created_at';
}

What clients may send ​

The form request checks a new order before your code sees it. If any rule fails, the client gets a 422 error that says which field is wrong, and the controller never runs. Its rules are also the request body's schema in the API reference, and describe() explains each field there.

php
<?php

namespace App\Http\Requests;

use App\Models\Order;
use FusionStack\Laravel\Http\ApiRequest;
use Illuminate\Validation\Rule;

final class StoreOrderRequest extends ApiRequest
{
    /** @return array<string, array<string, mixed>|string> */
    public function describe(): array
    {
        return [
            'total_cents' => ['description' => 'The order total in the smallest unit of the currency.', 'example' => 2500],
            'currency' => ['description' => 'EUR, GBP or USD.', 'example' => 'GBP'],
            'team' => 'The team placing the order.',
        ];
    }

    /** @return array<string, list<mixed>> */
    public function rules(): array
    {
        return [
            'data.type' => ['required', 'in:orders'],
            'data.attributes.total_cents' => ['required', 'integer', 'min:1'],
            'data.attributes.currency' => ['required', Rule::in(Order::CURRENCIES)],
            'data.relationships.team.data.id' => ['required', 'exists:teams,id'],
        ];
    }
}

The rules follow the JSON:API format: the order's values are under data.attributes, and the team under data.relationships.

The endpoints ​

The controller has one method per endpoint. #[Endpoint] gives each a summary and a description for the API reference.

php
<?php

namespace App\Http\Controllers;

use App\Http\Queries\OrderQuery;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use FusionStack\Laravel\OpenApi\Endpoint;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

final class OrderController
{
    #[Endpoint('List orders', 'Orders, newest first.')]
    public function index(OrderQuery $query): AnonymousResourceCollection
    {
        return OrderResource::collection($query->paginate());
    }

    #[Endpoint('Get an order')]
    public function show(OrderQuery $query, string $order): OrderResource
    {
        return new OrderResource($query->find($order));
    }

    #[Endpoint('Place an order', 'New orders are pending until they are paid.')]
    public function store(StoreOrderRequest $request): OrderResource
    {
        return new OrderResource(Order::query()->create([
            'team_id' => $request->integer('data.relationships.team.data.id'),
            'total_cents' => $request->integer('data.attributes.total_cents'),
            'currency' => $request->string('data.attributes.currency')->toString(),
        ]));
    }
}

Each method takes the class it needs, and Laravel provides it. index and show take the query, so a client's ?sort= or ?include= is checked before the database is asked. store takes the form request, so the order is valid by the time it runs.

Last, the routes connect URLs to the controller. Add the orders line to routes/api.php, inside the v1 group:

php
<?php

use App\Http\Controllers\OrderController;
use App\Http\Controllers\TeamController;
use App\Http\Controllers\TokenController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API routes
|--------------------------------------------------------------------------
|
| Routes in the fusion-stack middleware group get request IDs, API keys and
| scopes, rate limits, idempotency, HTTP caching, versioning and JSON:API
| errors, and appear in the OpenAPI document and the reference at /docs.
|
*/

// The root says where things are, for people and tools that open the bare URL. Change or remove it.
Route::get('/', fn () => response()->json([
    'name' => config('app.name'),
    'docs' => Route::has('fusion-stack.docs.reference') ? route('fusion-stack.docs.reference') : null,
    'openapi' => Route::has('fusion-stack.docs.openapi') ? route('fusion-stack.docs.openapi') : null,
], options: JSON_UNESCAPED_SLASHES))->name('home');

Route::prefix('v1')->middleware('fusion-stack')->group(function (): void {
    Route::post('tokens', [TokenController::class, 'store'])->name('tokens.store');

    // PATCH only: updates change just the attributes sent, so PUT would be misleading.
    Route::apiResource('teams', TeamController::class)->except('update');
    Route::patch('teams/{team}', [TeamController::class, 'update'])->name('teams.update');

    Route::apiResource('orders', OrderController::class)->only(['index', 'show', 'store']);
});

apiResource creates the three routes: GET /v1/orders, GET /v1/orders/{order} and POST /v1/orders. Routes in the fusion-stack group get the request IDs, errors and the rest of Fusion Stack's behaviour you saw in step 2.

Try it ​

Place an order for team 1, for £25.00:

sh
curl localhost:8000/v1/orders -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"orders","attributes":{"total_cents":2500,"currency":"GBP"},"relationships":{"team":{"data":{"type":"teams","id":"1"}}}}}'
json
{
  "data": {
    "id": "1",
    "type": "orders",
    "attributes": { "status": "pending", "total_cents": 2500, "currency": "GBP", "created_at": "2026-12-01T10:15:02.000000Z" }
  }
}

-d sends the body, which makes it a POST. application/vnd.api+json is JSON:API's content type.

Anyone can place an order

You did not send your key, and the order was placed anyway. The orders endpoints do not yet say which scope they need, so they need none. You fix that in step 5.

Fetch it by its ID:

sh
curl localhost:8000/v1/orders/1
json
{
  "data": {
    "id": "1",
    "type": "orders",
    "attributes": { "status": "pending", "total_cents": 2500, "currency": "GBP", "created_at": "2026-12-01T10:15:02.000000Z" }
  }
}

Now try an order in yen, which the shop does not take:

sh
curl localhost:8000/v1/orders -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"orders","attributes":{"total_cents":2500,"currency":"JPY"},"relationships":{"team":{"data":{"type":"teams","id":"1"}}}}}'
json
{
  "errors": [
    {
      "status": "422",
      "code": "validation_failed",
      "title": "Validation failed",
      "detail": "This field is invalid.",
      "source": { "pointer": "/data/attributes/currency" },
      "meta": { "request_id": "req_01m8rc4m2a8wz1tqk3v6d9x7hb" }
    }
  ]
}

source.pointer says which field is wrong, so a form can show the message next to it.

Open http://localhost:8000/docs in your browser: the three orders endpoints are there, with your descriptions, the request body's schema, and examples made by your factory.

The command fails with "Class not found"

A file is in the wrong folder, or its namespace line does not match its folder. Compare the path shown above each file with yours.

A request returns a 500 error

Laravel writes the full error to storage/logs/laravel.log, in the api folder. Its last lines say what went wrong, and the file and line where it happened. Most often a column name in the migration and the model differ, or php artisan migrate was not run.

The order is placed for a team that does not exist

It is not: exists:teams,id in the form request rejects it with a 422, pointing at /data/relationships/team/data/id. Check that you are sending the ID of a team in the list from step 2.

Test it ​

Trying requests by hand shows the endpoints work today. Tests check that they keep working, every time you change something. The project uses Pest, and Fusion Stack adds helpers such as $this->api() and assertApiError(). Create a test file:

php
<?php

use App\Models\Order;
use App\Models\Team;

it('places a pending order for a team', function (): void {
    $team = Team::factory()->create();

    $this->api()->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'GBP'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) $team->id]]],
    ]])
        ->assertCreated()
        ->assertJsonApiResource('orders')
        ->assertJsonPath('data.attributes.status', 'pending');

    expect(Order::query()->sole()->team_id)->toBe($team->id);
});

it('rejects an order in a currency it does not take', function (): void {
    $this->api()->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'JPY'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) Team::factory()->create()->id]]],
    ]])
        ->assertApiError('validation_failed', 422)
        ->assertJsonPath('errors.0.source.pointer', '/data/attributes/currency');

    expect(Order::query()->count())->toBe(0);
});

it('lists orders, newest first', function (): void {
    $old = Order::factory()->create(['created_at' => now()->subDay()]);
    $new = Order::factory()->create();

    $this->api()->getJson('/v1/orders')
        ->assertJsonApiCollection('orders', 2)
        ->assertJsonPath('data.0.id', (string) $new->id)
        ->assertJsonPath('data.1.id', (string) $old->id);
});

Each test starts with an empty database, so tests cannot affect each other. Run them, with the style and type checks:

sh
composer check
text
Tests: … passed (… assertions)

composer check runs three tools: Pint checks the code's style, PHPStan its types, and Pest the tests. One test checks that every endpoint and field is described in the API reference, so a missing description fails it too.

Pint says a file has style issues

Run composer format to fix the style, then composer check again.

Next: filtering, sorting and includes.

Released under the MIT License.