# Laravel API Versioning documentation (v10.x)

> Canonical: https://pharaonic.dev/packages/laravel/api-versioning/10.x  
> Version: v10.x (latest release 10.0.2, 2026-11-23)  
> Install: composer require pharaonic/laravel-api-versioning  
> Repository: https://github.com/Pharaonic/laravel-api-versioning  
> All versions: https://pharaonic.dev/packages/laravel/api-versioning/13.x.md https://pharaonic.dev/packages/laravel/api-versioning/12.x.md https://pharaonic.dev/packages/laravel/api-versioning/11.x.md https://pharaonic.dev/packages/laravel/api-versioning/10.x.md https://pharaonic.dev/packages/laravel/api-versioning/9.x.md https://pharaonic.dev/packages/laravel/api-versioning/8.x.md https://pharaonic.dev/packages/laravel/api-versioning/7.x.md https://pharaonic.dev/packages/laravel/api-versioning/6.x.md

:::badges
- Laravel Package {color=blue}
- v10.0.2 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# Laravel API Versioning

API Versioning adds versions to the routes you already write with Laravel's `Route` facade. A request names its version in a header, the query string, the path or anything your own resolver reads; the package validates it, checks that the endpoint exists in that version, and can run a different controller per version from one route. JSON resources keep Laravel's `JsonResource` and gain `whenVersion()`.

:::success AI Ready
API Versioning ships Laravel Boost resources: a guideline loaded in every session and an `api-versioning-development` skill loaded when your agent works on versioned endpoints. Run `php artisan boost:install` and Claude Code, Cursor, Codex, Copilot or Gemini CLI write correct versioned routes, controllers and resources. See [AI Ready](#ai-ready).
:::

:::features
### Native Routes
Route::version(), sinceVersion(), untilVersion() and versions() work with get, post, match, resources, groups, prefixes, names, domains and middleware.

### Any Version Source
Header, query string, path or a custom resolver, with deterministic errors for missing, unknown and conflicting versions.

### Controller per Version
One route per method and URI serves a controller per version, with its own middleware, bindings and policies.

### Versioned Resources
whenVersion() removes fields entirely, and an opt-in map picks a resource class per version.

### Lifecycle Headers
Deprecation, Sunset and Link headers per version, and retired versions are rejected.

### Cache Safe
Everything works after route:cache and config:cache, and the version lives on the request only.

### Predictable Errors
Missing, unknown, conflicting, unavailable and retired versions each have an error code and a configurable status, and messages never repeat what the client sent.

### Checked at Registration
Unknown versions, constraints that leave no version, invalid controller maps and duplicate routes or names fail when routes load.

### AI Ready
Laravel Boost guideline and skill included, so php artisan boost:install teaches your coding agent the package.
:::

:::info No URL is forced
The package never adds `/api` or `/v1` to your URLs. Versions are route metadata; a path prefix is only added when you configure one.
:::

## Installation

Install the package with Composer. The service provider and the `Route`, `Request` and resource helpers are registered automatically.

### Requirements

- PHP 8.1, 8.2 or 8.3
- Laravel 10.x

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-api-versioning
```

### Publish Configuration

Publish the configuration file to `config/pharaonic/api-versioning.php`:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-versioning-config
```

Then list your versions, oldest first:

```php title="config/pharaonic/api-versioning.php"
'versions' => ['v1', 'v2', 'v3'],
```

:::success Installation Complete
You're all set! Add a version constraint or a version group to your API routes.
:::

## Configuration

The configuration lives in `config/pharaonic/api-versioning.php` (`pharaonic.api-versioning`). Every key is optional except `versions`.

| Key | Default | Description |
| --- | --- | --- |
| `versions` | `['v1']` | Supported versions, oldest first. Every comparison follows this order, never the names, so `2024-01`, `beta` or `v10` work. Names use letters, digits, `.`, `_` and `-`. |
| `default` | `null` | The version of a request that names none. `null` rejects such requests. |
| `resolvers` | `['path', 'header']` | Where a request names its version: `path`, `header`, `query` or a class implementing `VersionResolver`, in any combination. |
| `header` | `X-API-Version` | The header the `header` resolver reads. |
| `query` | `version` | The query parameter the `query` resolver reads. |
| `path.prefix` | `null` | A prefix template for `Route::version()` groups, such as `api/{version}` or `{version}`. |
| `path.name` | `null` | A route name prefix template for `Route::version()` groups, such as `{version}.`. |
| `path.parameter` | `version` | The route parameter a shared route reads its version from, as in `Route::prefix('{version}')`. |
| `status.missing` | `400` | Status when no version is given and there is no default. |
| `status.unknown` | `400` | Status for a version that is not declared. |
| `status.conflict` | `400` | Status when two sources name different versions. |
| `status.unavailable` | `404` | Status when the endpoint does not exist in the version. |
| `status.retired` | `410` | Status for a retired version. |
| `resource_fallback` | `none` | What `VersionedResources` does for a version without its own class: `none`, `base` or `previous`. |
| `lifecycle` | `[]` | Status, dates and link per version; see [Lifecycle Headers](#lifecycle). |

```php title="config/pharaonic/api-versioning.php"
return [
    'versions' => ['v1', 'v2', 'v3'],
    'default' => 'v1',
    'resolvers' => ['header', 'query'],
    'header' => 'X-API-Version',
    'lifecycle' => [
        'v1' => ['status' => 'deprecated', 'deprecated_at' => '2026-06-01', 'sunset_at' => '2027-01-01'],
    ],
];
```

:::warning Cache your configuration and routes together
Route constraints are checked against `versions` when routes are registered. After changing the version list, run `php artisan config:cache` and `php artisan route:cache` again.
:::

## Basic Usage

A route becomes versioned when it gets a version constraint, either from a group or on the route itself. Versioned routes resolve the request's version before anything else runs; other routes are untouched.

```php title="routes/api.php"
use App\Http\Controllers\LegacyController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ReportController;

Route::get('profile', [ProfileController::class, 'show'])->sinceVersion('v1');
Route::get('reports', [ReportController::class, 'index'])->sinceVersion('v2');
Route::get('legacy', [LegacyController::class, 'index'])->untilVersion('v2');
```

With `X-API-Version: v1`, `/reports` is not found and `/legacy` works; with `v3`, `/reports` works and `/legacy` is not found.

### Reading the Version

`Request::apiVersion()` returns the resolved `Version`, or `null` on a route that is not versioned:

```php title="app/Http/Controllers/ProfileController.php"
public function show(Request $request)
{
    $version = $request->apiVersion();

    $version->name();          // "v2"
    $version->is('v2');        // true
    $version->atLeast('v2');   // true
    $version->before('v3');    // true
}
```

### Resolution Order

For every versioned route the package:

1. asks every enabled resolver for a version and rejects unknown values;
2. rejects the request when two resolvers name different versions;
3. uses the configured `default` when no resolver found one, or rejects the request;
4. rejects retired versions, then versions the route is not available in;
5. selects the version's controller, when the route maps controllers.

:::tip Shared routes are the norm
Most endpoints exist in every version. Give them `->sinceVersion('v1')` (or wrap them in `Route::sinceVersion('v1')->group(...)`), and change them per version with `whenVersion()` in resources or with `->controllers()`.
:::

## Version Groups

`Route::version()` registers routes that belong to one version. It takes a closure or a route file, or returns a registrar that accepts Laravel's group attributes.

```php title="routes/api.php"
use App\Http\Controllers\UserV1Controller;

Route::version('v1', function () {
    Route::apiResource('users', UserV1Controller::class);
});

Route::version('v2')
    ->middleware('auth:api')
    ->group(base_path('routes/api/v2.php'));
```

`middleware()`, `prefix()`, `name()`, `domain()`, `where()` and `namespace()` are Laravel's own and compose with every outer group. Inside the group, `Route::get()`, `post()`, `match()`, `any()`, `resource()` and `apiResource()` work as usual, and nested `Route::prefix()`, `name()` and `middleware()` groups keep their meaning.

### Path Prefix Templates

Without configuration a version group adds no URL prefix, so in header or query mode two groups cannot both register `GET users`. To put the version in the URL, configure templates:

```php title="config/pharaonic/api-versioning.php"
'path' => [
    'prefix' => 'api/{version}',
    'name' => '{version}.',
],
```

```php title="routes/api.php"
use App\Http\Controllers\UserV1Controller;
use App\Http\Controllers\UserV2Controller;

Route::version('v1', function () {
    Route::get('users', [UserV1Controller::class, 'index'])->name('users'); // /api/v1/users, v1.users
});

Route::version('v2', function () {
    Route::get('users', [UserV2Controller::class, 'index'])->name('users'); // /api/v2/users, v2.users
});
```

The template is added inside every prefix and name already in effect, including the ones chained on `Route::version()`: `Route::prefix('services')` around it gives `services/api/v1/users`, and `Route::version('v1')->prefix('admin')` gives `admin/api/v1/users`. A route registered under a template knows its version from the path, so the request needs no header, and a header that names another version is a conflict.

### Constraint Groups

`Route::versions()`, `Route::sinceVersion()` and `Route::untilVersion()` constrain a group without adding a prefix. They are the way to version resource routes, because `Route::apiResource()` returns a pending registration rather than a route:

```php title="routes/api.php"
use App\Http\Controllers\ExportController;
use App\Http\Controllers\ReportController;

Route::sinceVersion('v2')->middleware('auth:api')->group(function () {
    Route::apiResource('reports', ReportController::class);
});

Route::versions('v1', 'v2')->group(function () {
    Route::get('legacy/export', [ExportController::class, 'legacy']);
});
```

Constraints combine: `Route::sinceVersion('v2')->untilVersion('v3')`, and nested groups and route-level constraints always narrow.

:::warning One version group at a time
`Route::version()` groups cannot be nested. Inside a version group, use constraint groups or route constraints.
:::

### Registering a Single Route

The registrar also registers one route:

```php title="routes/api.php"
use App\Http\Controllers\ReportController;

Route::version('v2')->middleware('auth:api')->get('reports', [ReportController::class, 'index']);
```

Resources need `->group()`.

## Route Constraints

Every route gets the same constraints as groups:

```php title="routes/api.php"
use App\Http\Controllers\LegacyController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\WindowController;

Route::get('profile', [ProfileController::class, 'show'])->versions('v1', 'v2', 'v3');
Route::get('reports', [ReportController::class, 'index'])->sinceVersion('v2');
Route::get('legacy', [LegacyController::class, 'index'])->untilVersion('v2');
Route::get('window', [WindowController::class, 'index'])->sinceVersion('v2')->untilVersion('v3');
```

| Method | Available in |
| --- | --- |
| `->versions('v1', 'v3')` | exactly the listed versions (a list or an array, no duplicates) |
| `->sinceVersion('v2')` | v2 and every later version, including versions added later |
| `->untilVersion('v2')` | v2 and every earlier version |

Both bounds are inclusive and follow the order of `versions` in the configuration. Unknown versions, duplicates and constraints that leave no version fail when the routes are registered, with the route in the message.

### Shared Routes with a Path Parameter

A single route can take the version from its own URL:

```php title="routes/api.php"
use App\Http\Controllers\ProfileController;

Route::prefix('api/{version}')->group(function () {
    Route::get('profile', [ProfileController::class, 'show'])->versions('v1', 'v2');
});
```

`/api/v2/profile` resolves `v2`, `/api/v3/profile` is not found and `/api/v9/profile` is an unknown version. The `{version}` parameter is removed before route model binding and before the controller is called, so it never shifts controller arguments and never reaches `Route::bind('version')`. The parameter name is `path.parameter`.

:::warning A `{version}` parameter of your own
On a versioned route, the `path.parameter` route parameter always means the API version. When your URLs already use `{version}` for something else, such as `/documents/{document}/versions/{version}`, set `path.parameter` to another name, such as `api_version`.
:::

### Duplicate Definitions

Laravel silently keeps the last of two routes with the same method and URI. For versioned routes that would hide one version, so the package fails instead: two version groups or two versioned routes with the same method and URI, or a plain route that replaces a versioned one, are registration errors. Serve every version of an endpoint from one route (constraints or `->controllers()`), or give each version its own path prefix.

## Version Controllers

`->controllers()` maps versions to controllers on one route:

```php title="routes/api.php"
use App\Http\Controllers\ShowUserV3Controller;
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserV1Controller;

Route::get('users/{user}', [UserController::class, 'show'])->controllers([
    'v1' => [UserV1Controller::class, 'show'],
    'v2' => ['App\Http\Controllers\UserV2Controller', 'show'],
    'v3' => ShowUserV3Controller::class, // invokable
]);
```

`GET /users/1` with `X-API-Version: v2` runs `UserV2Controller@show`. Actions are `Class@method`, `[Class::class, 'method']` or an invokable class name; string actions get the group namespace like Laravel's own. Each one is checked when the route is registered: an unknown version, a missing class or method, a closure, or a version the route is not available in is an error.

### Laravel's Pipeline, per Version

The controller is selected when the route is matched, before Laravel gathers the route's middleware. Everything after that is Laravel's own:

- the controller's constructor injection and its `$this->middleware()` (including `only` and `except`);
- implicit and explicit route model binding, scoped bindings and missing models (404);
- method injection, `authorize()`, policies and the `can` middleware.

### No Silent Fallback

A version without a mapping is not found (`status.unavailable`, 404 by default). The route's own controller (`UserController@show` above) is used only when you say so:

```php title="routes/api.php"
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserV3Controller;

Route::get('users', [UserController::class, 'index'])
    ->controllers(['v3' => [UserV3Controller::class, 'index']], true); // v1 and v2 use UserController@index
```

Combine maps with constraints to stop at a version: `->controllers([...], true)->untilVersion('v3')`.

### Names, URLs and route:list

The route keeps its name and its own action, so `route('users.show', $user)`, `action([UserController::class, 'show'])` and `route:list` show the definition you wrote. One route name covers every version of the endpoint.

:::info Why one route per URI
In header and query mode every version shares the URL, and Laravel can only match one route per method and URI. The package keeps that single route and changes only which controller serves the request.
:::

## Resolving the Version

`resolvers` lists the sources a request may use. All enabled sources are read on every versioned request:

```php title="config/pharaonic/api-versioning.php"
'resolvers' => ['path', 'header', 'query'],
```

| Resolver | Reads | Example |
| --- | --- | --- |
| `path` | the `path.parameter` route parameter, or the version of a `Route::version()` group registered under `path.prefix` | `/api/v2/users` |
| `header` | the `header` request header | `X-API-Version: v2` |
| `query` | the `query` parameter | `/users?version=v2` |

- An unknown value from any source is rejected, so are arrays such as `?version[]=v1`, and empty values count as absent.
- Two sources naming different versions are a conflict; the same version twice is fine.
- Without any value, `default` is used, or the request is rejected.

### Vary

When the `header` resolver is enabled, versioned responses get `Vary: X-API-Version` (merged with any `Vary` your response already has), so shared caches keep one response per version. Query and path versions are part of the URL and need nothing.

### Custom Resolvers

A resolver returns the raw version the request carries, or `null`:

```php title="app/Http/AcceptHeaderVersion.php"
namespace App\Http;

use Illuminate\Http\Request;
use Pharaonic\Laravel\ApiVersioning\Contracts\VersionResolver;

class AcceptHeaderVersion implements VersionResolver
{
    public function resolve(Request $request): ?string
    {
        // Accept: application/vnd.example.v2+json
        preg_match('#application/vnd\.example\.([^+;,\s]+)\+json#', (string) $request->headers->get('Accept'), $matches);

        return $matches[1] ?? null;
    }
}
```

```php title="config/pharaonic/api-versioning.php"
'resolvers' => ['header', App\Http\AcceptHeaderVersion::class],
```

The package validates what it returns and compares it with the other sources. Resolvers are made from the container on every request, so they may take dependencies but should not keep request state. A domain-based version (`v2.api.example.com`) is a custom resolver that reads `$request->getHost()`.

## Versioned Resources

Resources stay Laravel's `JsonResource`. The package registers `whenVersion()` as a `JsonResource` macro, so every resource can use it:

```php title="app/Http/Resources/UserResource.php"
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->whenVersion('>=v2', fn () => $this->email),
            'legacy_name' => $this->whenVersion('<v2', fn () => $this->name),
            'plan' => $this->whenVersion('v3', 'premium', 'basic'),
        ];
    }
}
```

| Expression | Matches |
| --- | --- |
| `v2` or `=v2` | exactly v2 |
| `>=v2` / `>v2` | v2 and later / later than v2 |
| `<=v2` / `<v2` | v2 and earlier / earlier than v2 |

When the expression does not match, the field is removed with Laravel's `MissingValue`, never sent as `null`, and a closure value is never called, so its queries never run. With a third argument the field gets that default instead. Unknown versions and invalid expressions throw. A resource rendered without a resolved version (a console command, a queued job, a route that is not versioned) matches no expression.

Nested resources, `when()`, `whenLoaded()`, `mergeWhen()`, collections and paginated collections keep Laravel's behavior and use the same request version.

:::info The InteractsWithApiVersion trait
The `Pharaonic\Laravel\ApiVersioning\Concerns\InteractsWithApiVersion` trait provides the same `whenVersion()`. Laravel 8 and earlier need it, because `JsonResource` is macroable from Laravel 9; resources that already use it keep working.
:::

### Resource Classes per Version

For structural changes, map a resource to version-specific classes in a service provider's `boot()` method:

```php title="app/Providers/AppServiceProvider.php"
use App\Http\Resources\UserResource;
use App\Http\Resources\UserV3Resource;
use Pharaonic\Laravel\ApiVersioning\VersionedResources;

public function boot()
{
    $this->app->make(VersionedResources::class)->register(UserResource::class, [
        'v3' => UserV3Resource::class,
    ], 'base');
}
```

The map lives as long as the application, which is the whole worker under Laravel Octane, so register it while the application boots, never during a request. A resource can be registered once; registering it again throws a `LogicException`.

Then build resources through the service:

```php title="app/Http/Controllers/UserController.php"
public function index(VersionedResources $resources)
{
    return $resources->collection(UserResource::class, User::paginate());
}

public function show(VersionedResources $resources, User $user)
{
    return $resources->make(UserResource::class, $user);
}
```

`make()` returns the resolved resource, `collection()` returns Laravel's own collection of it (pagination `meta`, `links` and wrapping unchanged), and `resolve(UserResource::class)` returns the class name. `new UserResource($user)` is never intercepted.

| Fallback | A version without its own class |
| --- | --- |
| `none` (default) | throws a `LogicException` |
| `base` | uses the registered class (`UserResource`) |
| `previous` | uses the closest earlier mapped class, else the registered class |

Set the default with `resource_fallback`, or per resource with the third argument of `register()`. The newest class is never used for a version it was not mapped to.

## Lifecycle Headers

Each version has a lifecycle status:

```php title="config/pharaonic/api-versioning.php"
'lifecycle' => [
    'v1' => ['status' => 'retired', 'sunset_at' => '2026-01-01'],
    'v2' => [
        'status' => 'deprecated',
        'deprecated_at' => '2026-06-01',
        'sunset_at' => '2027-01-01',
        'link' => 'https://example.com/docs/migrating-to-v3',
    ],
    'v3' => ['status' => 'sunset-announced', 'sunset_at' => '2028-01-01'],
],
```

| Status | Responses |
| --- | --- |
| `active` (default) | no lifecycle headers |
| `deprecated` | `Deprecation: @1780272000` (RFC 9745, needs `deprecated_at`), `Sunset` when `sunset_at` is set, `Link: <…>; rel="deprecation"` when `link` is set |
| `sunset-announced` | `Sunset: Fri, 01 Jan 2027 00:00:00 GMT` (RFC 8594, needs `sunset_at`), `Deprecation` when `deprecated_at` is set, `Link: <…>; rel="sunset"` |
| `retired` | the request is rejected with `status.retired` (410 by default) and the `Sunset` header when set |

Dates are read in UTC. A sunset date is only announced: a version stops being served when you set its status to `retired`, never automatically. Headers your application already sets are kept, `Link` values are added next to yours, and response bodies are never changed.

## Errors

Rejected requests throw `Pharaonic\Laravel\ApiVersioning\Exceptions\ApiVersionException`, an `HttpException` that Laravel renders like any other. Messages never repeat what the client sent.

| `errorCode()` | Default status | When |
| --- | --- | --- |
| `ApiVersionException::MISSING` (`MISSING_API_VERSION`) | 400 | no version and no `default` |
| `ApiVersionException::UNKNOWN` (`UNKNOWN_API_VERSION`) | 400 | a version that is not declared |
| `ApiVersionException::CONFLICT` (`VERSION_CONFLICT`) | 400 | two sources name different versions |
| `ApiVersionException::UNAVAILABLE` (`API_VERSION_UNAVAILABLE`) | 404 | the endpoint does not exist in the version |
| `ApiVersionException::RETIRED` (`API_VERSION_RETIRED`) | 410 | the version is retired |

Change the statuses with `status.*`. When the header resolver is enabled, these errors carry `Vary` too. To use your own error format, render the exception in your exception handler:

```php title="app/Exceptions/Handler.php"
use Pharaonic\Laravel\ApiVersioning\Exceptions\ApiVersionException;

public function render($request, Throwable $e)
{
    if ($e instanceof ApiVersionException) {
        return response()->json(['error' => $e->errorCode()], $e->getStatusCode(), $e->getHeaders());
    }

    return parent::render($request, $e);
}
```

Version errors are found right after the route is matched, before the route's middleware: a request with an unknown version gets 400 even when the route needs authentication.

### Registration Errors

Mistakes in route definitions fail when the routes are registered, with the route in the message: unknown or duplicate versions, constraints that leave no version, invalid controller maps, nested `Route::version()` groups, duplicate method and URI definitions, and duplicate route names in version groups. They are `InvalidArgumentException` or `LogicException`, and they also stop `route:cache` and other Artisan commands, which load the routes.

## Route Caching and Workers

### route:cache and config:cache

Version constraints and controller maps are stored as plain strings in each route's action, so they are part of the route cache:

```bash title="Terminal" no-line-numbers
php artisan config:cache
php artisan route:cache
```

The package is tested by caching the routes, booting a new application that only loads the cached file, and comparing routes and responses: header controllers, model binding, controller middleware, policies, path groups and route names behave the same. `route:clear` and a rebuild work as usual.

:::warning Rebuild both caches together
Routes are validated against `versions` when they are registered. After changing `versions`, rebuild the config cache and the route cache.
:::

### Long-running Workers

The resolved version is stored on the request (`$request->attributes`), never in a static property or a singleton, so a worker that serves many requests (Laravel Octane, queue workers rendering resources, sequential test requests) never carries a version from one request to the next. The package's services only hold configuration.

Laravel reuses matched route objects between requests and keeps per-request state on them, such as their parameters and controller instance. For a route with `->controllers()`, the package sets the version's controller the same way, on every request before anything reads it, and points the route back at its own action when the request leaves it.

Two things stay with the application, not the request:

- Resource maps: register them with `VersionedResources::register()` while the application boots (a service provider's `boot()`), never in a middleware or a controller.
- Custom resolvers: read the request passed to `resolve(Request $request)`. Do not inject the request or keep it on the resolver.

:::info Tested
Repeated requests with alternating versions on one application are tested, including controller middleware, and so are services resolved before the first request, as a worker resolves them. The package does not run Laravel Octane itself in its test suite.
:::

## AI Ready

Laravel API Versioning is AI ready. It ships [Laravel Boost](https://laravel.com/docs/boost) resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to use the package.

### Install

With Laravel Boost in your application, run:

```bash title="Terminal" no-line-numbers
php artisan boost:install
```

Boost finds the package's guideline and skill in `vendor/` and adds them for the agents you choose. After updating the package, refresh them with:

```bash title="Terminal" no-line-numbers
php artisan boost:update
```

### What the Agent Learns

| Resource | Loaded | Covers |
| --- | --- | --- |
| Guideline (`resources/boost/guidelines/core.blade.php`) | In every session | Declaring versions, version groups and route constraints, controllers per version, `$request->apiVersion()` and `whenVersion()` |
| Skill `api-versioning-development` | When the agent works on versioned endpoints | Every public method, the configuration, resolvers, versioned resource classes, lifecycle headers, errors, pitfalls and testing |

:::tip Keep Them Current
Add `@php artisan boost:update --ansi` to your Composer `post-update-cmd` scripts so the agent always matches the installed release.
:::

## API Reference

### Route (static, on the router)

| Method | Description | Returns |
| --- | --- | --- |
| `Route::version(string $version, Closure\|string\|null $routes = null)` | Routes that belong to one version; with routes it registers the group, without it returns a registrar | `VersionedRouteRegistrar\|null` |
| `Route::versions(string\|array ...$versions)` | A group available in the listed versions | `VersionedRouteRegistrar` |
| `Route::sinceVersion(string $version)` | A group available from a version on | `VersionedRouteRegistrar` |
| `Route::untilVersion(string $version)` | A group available up to a version | `VersionedRouteRegistrar` |

### VersionedRouteRegistrar

| Method | Description | Returns |
| --- | --- | --- |
| `version()`, `versions()`, `sinceVersion()`, `untilVersion()` | Add constraints | `$this` |
| `middleware()`, `prefix()`, `name()`, `as()`, `domain()`, `where()`, `namespace()` | Laravel's group attributes | `$this` |
| `group(Closure\|string $routes)` | Register a closure or a route file | `void` |
| `get()`, `post()`, `put()`, `patch()`, `delete()`, `options()`, `any()`, `match()` | Register one route | `Illuminate\Routing\Route` |

### Route (on a route)

| Method | Description | Returns |
| --- | --- | --- |
| `->versions(string\|array ...$versions)` | Available in the listed versions | `Route` |
| `->sinceVersion(string $version)` | Available from a version on | `Route` |
| `->untilVersion(string $version)` | Available up to a version | `Route` |
| `->controllers(array $controllers, bool $fallback = false)` | A controller per version; with `$fallback`, unmapped versions use the route's own controller | `Route` |

### Request

| Method | Description | Returns |
| --- | --- | --- |
| `$request->apiVersion()` | The resolved version, `null` when the route is not versioned | `Version\|null` |

### JsonResource

| Method | Description | Returns |
| --- | --- | --- |
| `$this->whenVersion(string $expression, mixed $value, mixed $default = null)` | `$value` (a closure is called) when the request version matches; otherwise `$default` when given, else Laravel's `MissingValue` | `mixed` |

### Version

| Method | Description | Returns |
| --- | --- | --- |
| `name()` | The version name; also `(string) $version` | `string` |
| `is($version)` | Same version | `bool` |
| `atLeast($version)` / `atMost($version)` | Same or later / same or earlier | `bool` |
| `after($version)` / `before($version)` | Later / earlier | `bool` |

Arguments are a version name or a `Version`; unknown names throw `InvalidArgumentException`.

### VersionRegistry

Resolve it from the container.

| Method | Description | Returns |
| --- | --- | --- |
| `all()` | Declared versions, oldest first | `list<string>` |
| `has(string $name)` | Whether a version is declared | `bool` |
| `get(string $name)` | A version | `Version` |
| `default()` | The default version | `Version\|null` |
| `compare($a, $b)` | Negative, zero or positive by declared order | `int` |
| `status($version)` | `active`, `deprecated`, `sunset-announced` or `retired` | `string` |

### VersionedResources

| Method | Description | Returns |
| --- | --- | --- |
| `register(string $resource, array $versions, ?string $fallback = null)` | Map a resource to classes per version | `void` |
| `resolve(string $resource, Version\|string\|null $version = null)` | The class for a version (the request's by default) | `class-string` |
| `make(string $resource, mixed $value)` | A resource of the resolved class | `JsonResource` |
| `collection(string $resource, mixed $value)` | Laravel's collection of the resolved class | `AnonymousResourceCollection` |

### Other

| Name | Description |
| --- | --- |
| `Concerns\InteractsWithApiVersion` | Trait providing the same `whenVersion()`, for resources written for Laravel 8 and earlier |
| `Contracts\VersionResolver` | `resolve(Request $request): ?string` for custom resolvers |
| `Exceptions\ApiVersionException` | `errorCode()` plus the `MISSING`, `UNKNOWN`, `CONFLICT`, `UNAVAILABLE` and `RETIRED` constants |

## Examples

### 1. Header Versioning with Shared Routes

Every endpoint lives once; versions change controllers or fields.

```php title="routes/api.php"
use App\Http\Controllers\TeamController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserV2Controller;

Route::sinceVersion('v1')->group(function () {
    Route::get('users', [UserController::class, 'index']);
    Route::get('users/{user}', [UserController::class, 'show'])->controllers([
        'v1' => [UserController::class, 'show'],
        'v2' => [UserV2Controller::class, 'show'],
    ], true);
});

Route::sinceVersion('v2')->group(function () {
    Route::apiResource('teams', TeamController::class);
});
```

### 2. Versions in the URL

- ===Configuration

  ```php title="config/pharaonic/api-versioning.php"
  'versions' => ['v1', 'v2'],
  'resolvers' => ['path'],
  'path' => ['prefix' => '{version}', 'name' => '{version}.'],
  ```

- ===Routes

  ```php title="routes/api.php"
  Route::version('v1', function () {
      Route::apiResource('users', 'V1\UserController');
  });

  Route::version('v2')->middleware('auth:api')->group(function () {
      Route::apiResource('users', 'V2\UserController');
  });

  // /api/v1/users → v1.users.index, /api/v2/users → v2.users.index
  ```

### 3. Adding a Field in v2

```php title="app/Http/Resources/OrderResource.php"
public function toArray($request)
{
    return [
        'id' => $this->id,
        'total' => $this->total,
        'currency' => $this->whenVersion('>=v2', fn () => $this->currency),
        'items' => OrderItemResource::collection($this->whenLoaded('items')),
    ];
}
```

### 4. Retiring a Version

```php title="config/pharaonic/api-versioning.php"
'lifecycle' => [
    'v1' => ['status' => 'deprecated', 'deprecated_at' => '2026-06-01', 'sunset_at' => '2026-12-31', 'link' => 'https://example.com/v2-migration'],
],
// After the sunset date: 'v1' => ['status' => 'retired'], and v1 requests get 410.
```

## Troubleshooting

### Every request returns 400 "An API version is required."

The route is versioned and the request names no version. Send the header or query parameter, or set `default`.

### A route returns 404 for one version

The route is not available in that version: check its constraints and its group's, and its `->controllers()` map. A version without a mapped controller is not found unless the route falls back to its own controller.

### "Route [GET|HEAD /users] is registered more than once"

Two version groups or two versioned routes register the same method and URI, which only works when the version is in the path. Use one route with constraints or `->controllers()`, or configure `path.prefix`.

### "Route name [users] is already registered"

Two version groups give a route the same name. Configure `path.name` (`'{version}.'`) or chain `->name('v2.')` on the version group.

### The controller receives "v2" as its first argument

The route is not versioned, so the package does not remove the `{version}` parameter. Add a constraint to the route or its group.

### route:cache fails with an invalid controller

`->controllers()` checks every class and method when the routes load, and Artisan commands load the routes. Fix the map, or the route the message names.

### Changes to versions have no effect

The configuration or routes are cached. Run `php artisan config:cache` and `php artisan route:cache` again, or clear both.
