Skip to content

Attributes and middleware ​

Fusion Stack reads PHP attributes on controllers, resources, form requests, queries and error codes. An attribute on a controller class applies to each of its actions; one on an action wins over the class's.

AttributeGoes onWhat it does
#[Endpoint]Action, controller or closureSummary and description in the API reference.
#[RequiresScope]Action or controllerThe scope a request needs.
#[Describe]Resource, form request or queryA field's description, example and allowed values.
#[Description]Error code enum caseWhat an error code means.
#[CacheControl]Action or controllerThe Cache-Control header.
#[CacheResponse]Action or controllerCaches responses on the server.
#[McpTool]Action or closureExposes the endpoint as an MCP tool.
#[McpResource]Action or closureExposes the endpoint as an MCP resource.

#[Endpoint] ​

FusionStack\Laravel\OpenApi\Endpoint describes an endpoint in the OpenAPI document and the API reference.

php
#[Endpoint('List orders', 'Orders for the authenticated team, newest first.')]
public function index(OrderQuery $query): AnonymousResourceCollection
ArgumentDefaultWhat it does
summarynoneA short title, such as List orders.
descriptionnoneMore detail, in Markdown.
tagsThe first path segment after the version prefixGroups endpoints in the reference.
resourceFrom the return typeThe JsonApiResource class the action returns, when its return type does not say.
status200, or 201 for a POST returning a resourceThe success status.
hiddenfalseLeaves the endpoint out of the document.

On a closure route, put it on the closure: Route::get('ping', #[Endpoint('Ping')] fn () => []). api:docs:lint reports endpoints without a summary.

#[RequiresScope] ​

FusionStack\Laravel\Auth\RequiresScope names a scope the request needs. Guests get 401 unauthenticated, and clients without the scope get 403 insufficient_scope, with the scope in the error's meta.required_scope. Repeat it to require several. An endpoint without one needs no credentials.

php
#[RequiresScope('orders:write', 'Place and change orders.')]
public function store(StoreOrderRequest $request): OrderResource
ArgumentWhat it does
scopeThe scope, such as orders:write. A client with * has every scope.
descriptionWhat the scope allows, for the API reference. Give it once per scope.

For a route without a controller, use the scope middleware instead.

#[Describe] ​

FusionStack\Laravel\OpenApi\Describe describes one field. Repeat it on the class, once per field:

php
#[Describe('status', 'Where the order is in fulfilment.', values: [
    'pending' => 'Placed, awaiting payment',
    'paid' => 'Paid, not yet shipped',
])]
#[Describe('total', 'The total in the smallest unit of the currency.', example: 2500)]
final class OrderResource extends JsonApiResource
ArgumentWhat it does
fieldThe field, named as in the latest version.
descriptionWhat the field means.
exampleAn example value, used in request examples. For fields that are not columns, such as accessors, it also sets the type.
valuesWhat each allowed value means. It also limits the field to those values in the schema.

What a field is depends on the class:

OnA field is
A JsonApiResourceAn attribute or relationship.
A form requestA rule key, or the attribute or relationship name alone for JSON:API bodies: total for data.attributes.total.
An ApiQueryA filter.

Resources and form requests can also return descriptions from a describe() method, whose entries win over the attributes. Each entry is a description, or an array with description, example and values:

php
public function describe(): array
{
    return [
        'currency' => ['description' => 'EUR, GBP or USD.', 'example' => 'GBP'],
        'team' => 'The team placing the order.',
    ];
}

#[Description] ​

FusionStack\Laravel\OpenApi\Description explains an error code in the API reference: when clients get it, and what to do. Cases without one are described by their title. See errors.

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

#[CacheControl] ​

FusionStack\Laravel\Caching\CacheControl sets the Cache-Control header of successful GET responses, instead of api.http_cache.cache_control and any cache-control route middleware.

php
#[CacheControl(maxAge: 60, private: true)]
public function show(OrderQuery $query, string $order): OrderResource
ArgumentDirective
maxAgemax-age=…
sMaxAges-maxage=…, for shared caches
publicpublic. It cannot be combined with private.
privateprivate
noCacheno-cache
noStoreno-store
mustRevalidatemust-revalidate
staleWhileRevalidatestale-while-revalidate=…
immutableimmutable

See caching for when to use each.

#[CacheResponse] ​

FusionStack\Laravel\Caching\CacheResponse keeps successful GET responses on the server, in the latest version's shape, so one entry serves every pinned version. Responses carry X-Response-Cache: hit or miss.

php
#[CacheResponse(ttl: 60, tags: ['orders:{order}', 'teams'])]
public function show(OrderQuery $query, string $order): OrderResource
ArgumentDefaultWhat it does
ttl60Seconds to keep an entry.
tags[]Flushing any of these drops the entry. {order} is replaced by the route parameter, so orders:{order} becomes orders:42.
sharedfalseShares entries between callers. Use it only for data every caller may see.

A model using the FusionStack\Laravel\Caching\FlushesResponseCache trait flushes its table's tag, such as orders, and its own, such as orders:42, when it is saved or deleted. Override responseCacheTags() to flush more.

WARNING

A cache hit skips the controller, so checks inside it, such as policies or ApiQuery::scope(), do not run. Entries are kept per client unless shared is true.

#[McpTool] ​

FusionStack\Mcp\McpTool, from the optional fusion-stack/mcp package, exposes an endpoint as an MCP tool. Nothing is exposed without it. See the MCP guide.

ArgumentDefaultWhat it does
nameThe endpoint's summary in snake case, such as list_ordersThe tool's name.
descriptionThe endpoint's summary and descriptionWhat the tool does.
destructivenoneRequired for endpoints that are not GET: true for deleting or cancelling, false for only adding.

#[McpResource] ​

FusionStack\Mcp\McpResource exposes a GET endpoint without path parameters as a read-only MCP resource, for reference data such as order statuses.

ArgumentDefault
uriapi:// and the endpoint's path, such as api://v1/order-statuses
nameThe endpoint's summary in snake case
descriptionThe endpoint's summary and description

Middleware ​

The fusion-stack group ​

Routes in the fusion-stack middleware group get Fusion Stack's behaviour, and appear in the OpenAPI document:

php
Route::prefix('v1')->middleware('fusion-stack')->group(function (): void {
    Route::apiResource('orders', OrderController::class);
});

It runs, in this order, which the package fixes:

  1. Request ID: reads or creates X-Request-Id.
  2. Client: authenticates the request with the configured guards.
  3. Version: resolves the version, and sets Api-Version on the response.
  4. Deprecation: sets Deprecation, Sunset and Link for deprecated versions.
  5. Route in version: 404 or 410 for routes the version does not have.
  6. Rate limit.
  7. Scopes: checks #[RequiresScope] and the scope middleware.
  8. Idempotency.
  9. Request transform: migrates older clients' bodies to the latest version.
  10. Response transform: migrates responses back to the client's version.
  11. HTTP cache: ETag, 304 Not Modified, Cache-Control and Vary.
  12. Response cache: #[CacheResponse].
  13. Legacy controllers: dispatches frozen actions for older versions.

Request IDs, authentication, rate limiting, versioning, idempotency, ETags and the response cache each have a switch in configuration.

scope ​

scope:orders:write requires a scope on routes without a controller to put #[RequiresScope] on. List several to require each:

php
Route::get('reports', fn () => ...)->middleware('scope:reports:read');

cache-control ​

cache-control:public,max-age=60 sets the Cache-Control header for a route or group's successful GET responses. #[CacheControl] on the controller wins over it.

Released under the MIT License.