Skip to content

6. A custom action: emailing an invoice ​

So far every endpoint creates or reads orders. Real APIs also do things: send an invoice, refund a payment, ship an order. In this step you add an endpoint that emails an order's invoice, and meet the pattern Fusion Stack recommends for actions like it.

An action as a resource ​

It is tempting to add POST /v1/orders/{order}/send-invoice. Instead, model the action as creating a resource: an invoice email. Sending an invoice becomes POST /v1/invoice-emails, with the order as a relationship.

This costs one small table, and gives you a lot for free:

  • History. Every invoice sent is a record you can list: who it went to, and when. "Did the customer get their invoice?" has an answer.
  • The same rules as everything else. Validation, scopes, errors, idempotency and the API reference work exactly as for orders.
  • Safe retries. Sending an email twice is a real mistake. You will see below how one header prevents it.

The table and the model ​

sh
php artisan make:model InvoiceEmail -m
text
INFO Model [app/Models/InvoiceEmail.php] created successfully.
INFO Migration [database/migrations/…_create_invoice_emails_table.php] created successfully.
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('invoice_emails', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
            $table->string('to');
            $table->text('message')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('invoice_emails');
    }
};
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

/**
 * @property int $id
 * @property int $order_id
 * @property string $to
 * @property string|null $message
 * @property Carbon|null $sent_at
 */
#[Fillable(['order_id', 'to', 'message', 'sent_at'])]
final class InvoiceEmail extends Model
{
    /** @return BelongsTo<Order, $this> */
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    /** @return array<string, string> */
    protected function casts(): array
    {
        return ['sent_at' => 'datetime'];
    }
}
sh
php artisan migrate
text
INFO Running migrations.
…_create_invoice_emails_table … DONE

The email ​

A Laravel mailable is one email: its subject and its content. Create the file:

php
<?php

namespace App\Mail;

use App\Models\Order;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

final class InvoiceMail extends Mailable
{
    public function __construct(public readonly Order $order, public readonly ?string $note = null) {}

    public function envelope(): Envelope
    {
        return new Envelope(subject: "Invoice for order {$this->order->id}");
    }

    public function content(): Content
    {
        $total = number_format($this->order->total_cents / 100, 2).' '.$this->order->currency;

        return new Content(htmlString: '<p>'.e($this->note ?? 'Thank you for your order.').'</p>'
            .'<p>Order '.$this->order->id.': '.e($total).', '.e($this->order->status).'.</p>');
    }
}

The project sends email to its log file, storage/logs/laravel.log, so you can see each one without an email account. In production you set MAIL_MAILER in .env to a real service, such as SMTP or Postmark.

An error of your own ​

Only paid or shipped orders have an invoice to send. When a client tries to send one for a pending order, it should get an error it can recognise, like the package's own. Add a code to the API's error codes, in app/Api/ErrorCode.php:

php
<?php

namespace App\Api;

use FusionStack\Laravel\Errors\ErrorCode as Contract;
use FusionStack\Laravel\OpenApi\Description;

/**
 * This API's own error codes, alongside the package's. Throw them with ApiException, and they
 * are documented in the API reference (config/api.php, `openapi.error_codes`).
 */
enum ErrorCode: string implements Contract
{
    #[Description('The email address or password is wrong.')]
    case InvalidCredentials = 'invalid_credentials';

    #[Description('Only paid and shipped orders have an invoice to send.')]
    case OrderNotPaid = 'order_not_paid';

    public function status(): int
    {
        return match ($this) {
            self::InvalidCredentials => 401,
            self::OrderNotPaid => 409,
        };
    }

    public function title(): string
    {
        return match ($this) {
            self::InvalidCredentials => 'Invalid credentials',
            self::OrderNotPaid => 'Order not paid',
        };
    }
}

409 Conflict means the request is valid, but the state of the order does not allow it. #[Description] explains the code in the API reference, so client developers know to handle it.

The resource, query and form request ​

These follow the same pattern as orders in step 3. The resource names its type invoice-emails, and the query only lists the emails of the order in the URL, with scope():

php
<?php

namespace App\Http\Resources;

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

#[Describe('to', 'The email address the invoice was sent to.')]
#[Describe('message', 'A note shown above the invoice, if any.')]
#[Describe('sent_at', 'When the email was sent.')]
#[Describe('order', 'The order whose invoice was sent.')]
final class InvoiceEmailResource extends JsonApiResource
{
    /** @var list<string> */
    public array $attributes = ['to', 'message', 'sent_at'];

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

    public function toType(Request $request): string
    {
        return 'invoice-emails';
    }
}
php
<?php

namespace App\Http\Queries;

use App\Models\InvoiceEmail;
use FusionStack\Laravel\Auth\ApiClient;
use FusionStack\Laravel\Query\ApiQuery;
use Illuminate\Database\Eloquent\Builder;

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

    protected ?string $type = 'invoice-emails';

    protected array $fields = [
        'invoice-emails' => ['to', 'message', 'sent_at', 'order'],
    ];

    protected string $defaultSort = '-created_at';

    /** Only the emails of the order in the URL: /v1/orders/{order}/invoice-emails. */
    protected function scope(Builder $query, ?ApiClient $client): void
    {
        $query->where('order_id', $this->request->route('order'));
    }
}
php
<?php

namespace App\Http\Requests;

use FusionStack\Laravel\Http\ApiRequest;

final class StoreInvoiceEmailRequest extends ApiRequest
{
    /** @return array<string, array<string, mixed>|string> */
    public function describe(): array
    {
        return [
            'to' => ['description' => 'The email address to send the invoice to.', 'example' => 'accounts@acme.test'],
            'message' => ['description' => 'A note to show above the invoice.', 'example' => 'Thanks for your order!'],
            'order' => 'The order whose invoice to send. It must be paid or shipped.',
        ];
    }

    /** @return array<string, list<mixed>> */
    public function rules(): array
    {
        return [
            'data.type' => ['required', 'in:invoice-emails'],
            'data.attributes.to' => ['required', 'email', 'max:255'],
            'data.attributes.message' => ['sometimes', 'nullable', 'string', 'max:2000'],
            'data.relationships.order.data.id' => ['required', 'exists:orders,id'],
        ];
    }
}

scope() runs before any filter or sort the client sends, so no query parameter can reach another order's emails. It is also where you would limit each caller to their own team's records.

The endpoints ​

php
<?php

namespace App\Http\Controllers;

use App\Api\ErrorCode;
use App\Http\Queries\InvoiceEmailQuery;
use App\Http\Requests\StoreInvoiceEmailRequest;
use App\Http\Resources\InvoiceEmailResource;
use App\Mail\InvoiceMail;
use App\Models\InvoiceEmail;
use App\Models\Order;
use FusionStack\Laravel\Auth\RequiresScope;
use FusionStack\Laravel\Errors\ApiException;
use FusionStack\Laravel\OpenApi\Endpoint;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Mail;

final class InvoiceEmailController
{
    #[RequiresScope('orders:read')]
    #[Endpoint("List an order's invoice emails", 'Every time the invoice was sent, newest first.')]
    public function index(InvoiceEmailQuery $query, string $order): AnonymousResourceCollection
    {
        Order::query()->findOrFail($order);

        return InvoiceEmailResource::collection($query->paginate());
    }

    #[RequiresScope('invoices:send', 'Email invoices to customers.')]
    #[Endpoint('Email an invoice', 'Sends the order\'s invoice. Send an Idempotency-Key header, so a retry does not send it twice.')]
    public function store(StoreInvoiceEmailRequest $request): InvoiceEmailResource
    {
        $order = Order::query()->findOrFail($request->integer('data.relationships.order.data.id'));

        if (! in_array($order->status, ['paid', 'shipped'], true)) {
            throw new ApiException(
                ErrorCode::OrderNotPaid,
                "Order {$order->id} is {$order->status}: only paid and shipped orders have an invoice.",
                pointer: '/data/relationships/order/data/id',
            );
        }

        $email = InvoiceEmail::query()->create([
            'order_id' => $order->id,
            'to' => $request->string('data.attributes.to')->toString(),
            'message' => $request->input('data.attributes.message'),
        ]);

        Mail::to($email->to)->send(new InvoiceMail($order, $email->message));
        $email->update(['sent_at' => now()]);

        return new InvoiceEmailResource($email);
    }
}

Sending an invoice needs its own scope, invoices:send. A program that places orders does not need to send invoices too, and the reporting key from step 5 can still list them, with orders:read.

Add the two routes inside the v1 group:

php
<?php

use App\Http\Controllers\InvoiceEmailController;
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']);

    Route::post('invoice-emails', [InvoiceEmailController::class, 'store'])->name('invoice-emails.store');
    Route::get('orders/{order}/invoice-emails', [InvoiceEmailController::class, 'index'])->name('orders.invoice-emails.index');
});

Try it ​

Order 2, from step 4's seeder, is paid. Send its invoice:

sh
curl localhost:8000/v1/invoice-emails -H "Authorization: Bearer $KEY" -H "Content-Type: application/vnd.api+json" \
  -H "Idempotency-Key: invoice-order-2" \
  -d '{"data":{"type":"invoice-emails","attributes":{"to":"accounts@acme.test","message":"Thanks for your order!"},"relationships":{"order":{"data":{"type":"orders","id":"2"}}}}}'
json
{
  "data": {
    "id": "1",
    "type": "invoice-emails",
    "attributes": { "to": "accounts@acme.test", "message": "Thanks for your order!", "sent_at": "2026-12-01T10:41:07.000000Z" }
  }
}

The email is in the log. Its subject:

sh
grep "Subject:" storage/logs/laravel.log | tail -n 1
text
Subject: Invoice for order 2

Retry safely ​

Suppose the connection dropped before your program saw the response. Did the email go? It cannot tell, so it sends the request again, with the same idempotency key:

sh
curl localhost:8000/v1/invoice-emails -H "Authorization: Bearer $KEY" -H "Content-Type: application/vnd.api+json" \
  -H "Idempotency-Key: invoice-order-2" \
  -d '{"data":{"type":"invoice-emails","attributes":{"to":"accounts@acme.test","message":"Thanks for your order!"},"relationships":{"order":{"data":{"type":"orders","id":"2"}}}}}'
json
{
  "data": {
    "id": "1",
    "type": "invoice-emails",
    "attributes": { "to": "accounts@acme.test", "message": "Thanks for your order!", "sent_at": "2026-12-01T10:41:07.000000Z" }
  }
}

The same response, with the same id. Fusion Stack saw the key again and replayed the first response, without running the controller: no second email was sent. An operation that is safe to repeat like this is idempotent. Your program chooses the key, one per invoice it means to send, such as a random ID it keeps until the request succeeds. The idempotency page has the details.

The order's history shows one email:

sh
curl -g "localhost:8000/v1/orders/2/invoice-emails?fields[invoice-emails]=to,sent_at" -H "Authorization: Bearer $KEY"
json
{
  "data": [{ "id": "1", "type": "invoice-emails", "attributes": { "to": "accounts@acme.test", "sent_at": "2026-12-01T10:41:07.000000Z" } }],
  "links": { "first": "http://localhost:8000/v1/orders/2/invoice-emails?…", "prev": null, "next": null },
  "meta": { "page": { "size": 25 } }
}

Break a rule ​

Order 1, from step 3, is still pending:

sh
curl localhost:8000/v1/invoice-emails -H "Authorization: Bearer $KEY" -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"invoice-emails","attributes":{"to":"accounts@acme.test"},"relationships":{"order":{"data":{"type":"orders","id":"1"}}}}}'
json
{
  "errors": [
    {
      "status": "409",
      "code": "order_not_paid",
      "title": "Order not paid",
      "detail": "Order 1 is pending: only paid and shipped orders have an invoice.",
      "source": { "pointer": "/data/relationships/order/data/id" },
      "meta": { "request_id": "req_01m8rhb4n6m2k8j4h2g6f8d0s2" }
    }
  ]
}

Your own error looks just like the package's. A web app can check code and show "Send the invoice once the order is paid" rather than a generic failure.

The retry sent a second email

The two requests must have the same Idempotency-Key, and the same body: a different body with the same key is refused with a 422 idempotency_key_mismatch, as it is probably a mistake. Without the header, each request is new.

Nothing is in storage/logs/laravel.log

Check MAIL_MAILER=log in .env. If you changed it to a real service, the email went there instead.

Test it ​

Mail::fake() stops tests sending real email, and lets them check what would have been sent:

php
<?php

use App\Mail\InvoiceMail;
use App\Models\InvoiceEmail;
use App\Models\Order;
use Illuminate\Support\Facades\Mail;

function invoiceEmail(Order $order, string $to = 'accounts@acme.test'): array
{
    return ['data' => [
        'type' => 'invoice-emails',
        'attributes' => ['to' => $to],
        'relationships' => ['order' => ['data' => ['type' => 'orders', 'id' => (string) $order->id]]],
    ]];
}

it('emails the invoice of a paid order, once per idempotency key', function (): void {
    Mail::fake();
    $order = Order::factory()->create(['status' => 'paid']);
    $api = $this->api()->withKey(apiKey('invoices:send'))->withIdempotencyKey('invoice-1');

    $api->postJson('/v1/invoice-emails', invoiceEmail($order))
        ->assertCreated()
        ->assertJsonApiResource('invoice-emails')
        ->assertJsonPath('data.attributes.to', 'accounts@acme.test');
    $api->postJson('/v1/invoice-emails', invoiceEmail($order))->assertCreated()->assertIdempotentReplay();

    Mail::assertSentCount(1);
    Mail::assertSent(InvoiceMail::class, fn (InvoiceMail $mail): bool => $mail->hasTo('accounts@acme.test') && $mail->order->is($order));
    expect(InvoiceEmail::query()->sole()->sent_at)->not->toBeNull();
});

it('refuses to email the invoice of an unpaid order', function (): void {
    Mail::fake();
    $order = Order::factory()->create(['status' => 'pending']);

    $this->api()->withKey(apiKey('invoices:send'))->postJson('/v1/invoice-emails', invoiceEmail($order))
        ->assertApiError('order_not_paid', 409)
        ->assertJsonPath('errors.0.source.pointer', '/data/relationships/order/data/id');

    Mail::assertNothingSent();
    expect(InvoiceEmail::query()->count())->toBe(0);
});

it("lists only that order's invoice emails", function (): void {
    Mail::fake();
    [$order, $other] = Order::factory(2)->create(['status' => 'shipped']);
    $api = $this->api()->withKey(apiKey('invoices:send', 'orders:read'));
    $api->postJson('/v1/invoice-emails', invoiceEmail($order, 'a@acme.test'))->assertCreated();
    $api->postJson('/v1/invoice-emails', invoiceEmail($other, 'b@acme.test'))->assertCreated();

    $api->getJson("/v1/orders/{$order->id}/invoice-emails")
        ->assertJsonApiCollection('invoice-emails', 1)
        ->assertJsonPath('data.0.attributes.to', 'a@acme.test');
    $api->getJson('/v1/orders/999/invoice-emails')->assertApiError('not_found', 404);
});

it('needs the invoices:send scope to email an invoice', function (): void {
    Mail::fake();

    $this->api()->withKey(apiKey('orders:read', 'orders:write'))
        ->postJson('/v1/invoice-emails', invoiceEmail(Order::factory()->create(['status' => 'paid'])))
        ->assertApiError('insufficient_scope', 403);

    Mail::assertNothingSent();
});
sh
composer check
text
Tests: … passed (… assertions)

Next: generate the SDK and build a Nuxt page.

Released under the MIT License.