Skip to content
Laravel Packagev12.0.2MIT LicenseAI Ready

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().

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.

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.

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.2, 8.3, 8.4 or 8.5
  • Laravel 12.x

#Composer Installation

Terminal
composer require pharaonic/laravel-api-versioning

#Publish Configuration

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

Terminal
php artisan vendor:publish --tag=api-versioning-config

Then list your versions, oldest first:

config/pharaonic/api-versioning.php
1'versions' => ['v1', 'v2', 'v3'],
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.

KeyDefaultDescription
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 -.
defaultnullThe 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.
headerX-API-VersionThe header the header resolver reads.
queryversionThe query parameter the query resolver reads.
path.prefixnullA prefix template for Route::version() groups, such as api/{version} or {version}.
path.namenullA route name prefix template for Route::version() groups, such as {version}..
path.parameterversionThe route parameter a shared route reads its version from, as in Route::prefix('{version}').
status.missing400Status when no version is given and there is no default.
status.unknown400Status for a version that is not declared.
status.conflict400Status when two sources name different versions.
status.unavailable404Status when the endpoint does not exist in the version.
status.retired410Status for a retired version.
resource_fallbacknoneWhat VersionedResources does for a version without its own class: none, base or previous.
lifecycle[]Status, dates and link per version; see Lifecycle Headers.
config/pharaonic/api-versioning.php
1return [
2 'versions' => ['v1', 'v2', 'v3'],
3 'default' => 'v1',
4 'resolvers' => ['header', 'query'],
5 'header' => 'X-API-Version',
6 'lifecycle' => [
7 'v1' => ['status' => 'deprecated', 'deprecated_at' => '2026-06-01', 'sunset_at' => '2027-01-01'],
8 ],
9];
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.

routes/api.php
1use App\Http\Controllers\LegacyController;
2use App\Http\Controllers\ProfileController;
3use App\Http\Controllers\ReportController;
4 
5Route::get('profile', [ProfileController::class, 'show'])->sinceVersion('v1');
6Route::get('reports', [ReportController::class, 'index'])->sinceVersion('v2');
7Route::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:

app/Http/Controllers/ProfileController.php
1public function show(Request $request)
2{
3 $version = $request->apiVersion();
4 
5 $version->name(); // "v2"
6 $version->is('v2'); // true
7 $version->atLeast('v2'); // true
8 $version->before('v3'); // true
9}

#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.
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.

routes/api.php
1use App\Http\Controllers\UserV1Controller;
2 
3Route::version('v1', function () {
4 Route::apiResource('users', UserV1Controller::class);
5});
6 
7Route::version('v2')
8 ->middleware('auth:api')
9 ->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:

config/pharaonic/api-versioning.php
1'path' => [
2 'prefix' => 'api/{version}',
3 'name' => '{version}.',
4],
routes/api.php
1use App\Http\Controllers\UserV1Controller;
2use App\Http\Controllers\UserV2Controller;
3 
4Route::version('v1', function () {
5 Route::get('users', [UserV1Controller::class, 'index'])->name('users'); // /api/v1/users, v1.users
6});
7 
8Route::version('v2', function () {
9 Route::get('users', [UserV2Controller::class, 'index'])->name('users'); // /api/v2/users, v2.users
10});

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:

routes/api.php
1use App\Http\Controllers\ExportController;
2use App\Http\Controllers\ReportController;
3 
4Route::sinceVersion('v2')->middleware('auth:api')->group(function () {
5 Route::apiResource('reports', ReportController::class);
6});
7 
8Route::versions('v1', 'v2')->group(function () {
9 Route::get('legacy/export', [ExportController::class, 'legacy']);
10});

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

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:

routes/api.php
1use App\Http\Controllers\ReportController;
2 
3Route::version('v2')->middleware('auth:api')->get('reports', [ReportController::class, 'index']);

Resources need ->group().

#Route Constraints

Every route gets the same constraints as groups:

routes/api.php
1use App\Http\Controllers\LegacyController;
2use App\Http\Controllers\ProfileController;
3use App\Http\Controllers\ReportController;
4use App\Http\Controllers\WindowController;
5 
6Route::get('profile', [ProfileController::class, 'show'])->versions('v1', 'v2', 'v3');
7Route::get('reports', [ReportController::class, 'index'])->sinceVersion('v2');
8Route::get('legacy', [LegacyController::class, 'index'])->untilVersion('v2');
9Route::get('window', [WindowController::class, 'index'])->sinceVersion('v2')->untilVersion('v3');
MethodAvailable 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:

routes/api.php
1use App\Http\Controllers\ProfileController;
2 
3Route::prefix('api/{version}')->group(function () {
4 Route::get('profile', [ProfileController::class, 'show'])->versions('v1', 'v2');
5});

/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.

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:

routes/api.php
1use App\Http\Controllers\ShowUserV3Controller;
2use App\Http\Controllers\UserController;
3use App\Http\Controllers\UserV1Controller;
4 
5Route::get('users/{user}', [UserController::class, 'show'])->controllers([
6 'v1' => [UserV1Controller::class, 'show'],
7 'v2' => ['App\Http\Controllers\UserV2Controller', 'show'],
8 'v3' => ShowUserV3Controller::class, // invokable
9]);

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:

routes/api.php
1use App\Http\Controllers\UserController;
2use App\Http\Controllers\UserV3Controller;
3 
4Route::get('users', [UserController::class, 'index'])
5 ->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.

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:

config/pharaonic/api-versioning.php
1'resolvers' => ['path', 'header', 'query'],
ResolverReadsExample
paththe path.parameter route parameter, or the version of a Route::version() group registered under path.prefix/api/v2/users
headerthe header request headerX-API-Version: v2
querythe 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:

app/Http/AcceptHeaderVersion.php
1namespace App\Http;
2 
3use Illuminate\Http\Request;
4use Pharaonic\Laravel\ApiVersioning\Contracts\VersionResolver;
5 
6class AcceptHeaderVersion implements VersionResolver
7{
8 public function resolve(Request $request): ?string
9 {
10 // Accept: application/vnd.example.v2+json
11 preg_match('#application/vnd\.example\.([^+;,\s]+)\+json#', (string) $request->headers->get('Accept'), $matches);
12 
13 return $matches[1] ?? null;
14 }
15}
config/pharaonic/api-versioning.php
1'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:

app/Http/Resources/UserResource.php
1namespace App\Http\Resources;
2 
3use Illuminate\Http\Resources\Json\JsonResource;
4 
5class UserResource extends JsonResource
6{
7 public function toArray($request)
8 {
9 return [
10 'id' => $this->id,
11 'name' => $this->name,
12 'email' => $this->whenVersion('>=v2', fn () => $this->email),
13 'legacy_name' => $this->whenVersion('<v2', fn () => $this->name),
14 'plan' => $this->whenVersion('v3', 'premium', 'basic'),
15 ];
16 }
17}
ExpressionMatches
v2 or =v2exactly v2
>=v2 / >v2v2 and later / later than v2
<=v2 / <v2v2 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.

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:

app/Providers/AppServiceProvider.php
1use App\Http\Resources\UserResource;
2use App\Http\Resources\UserV3Resource;
3use Pharaonic\Laravel\ApiVersioning\VersionedResources;
4 
5public function boot()
6{
7 $this->app->make(VersionedResources::class)->register(UserResource::class, [
8 'v3' => UserV3Resource::class,
9 ], 'base');
10}

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:

app/Http/Controllers/UserController.php
1public function index(VersionedResources $resources)
2{
3 return $resources->collection(UserResource::class, User::paginate());
4}
5 
6public function show(VersionedResources $resources, User $user)
7{
8 return $resources->make(UserResource::class, $user);
9}

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.

FallbackA version without its own class
none (default)throws a LogicException
baseuses the registered class (UserResource)
previoususes 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:

config/pharaonic/api-versioning.php
1'lifecycle' => [
2 'v1' => ['status' => 'retired', 'sunset_at' => '2026-01-01'],
3 'v2' => [
4 'status' => 'deprecated',
5 'deprecated_at' => '2026-06-01',
6 'sunset_at' => '2027-01-01',
7 'link' => 'https://example.com/docs/migrating-to-v3',
8 ],
9 'v3' => ['status' => 'sunset-announced', 'sunset_at' => '2028-01-01'],
10],
StatusResponses
active (default)no lifecycle headers
deprecatedDeprecation: @1780272000 (RFC 9745, needs deprecated_at), Sunset when sunset_at is set, Link: <…>; rel="deprecation" when link is set
sunset-announcedSunset: Fri, 01 Jan 2027 00:00:00 GMT (RFC 8594, needs sunset_at), Deprecation when deprecated_at is set, Link: <…>; rel="sunset"
retiredthe 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 statusWhen
ApiVersionException::MISSING (MISSING_API_VERSION)400no version and no default
ApiVersionException::UNKNOWN (UNKNOWN_API_VERSION)400a version that is not declared
ApiVersionException::CONFLICT (VERSION_CONFLICT)400two sources name different versions
ApiVersionException::UNAVAILABLE (API_VERSION_UNAVAILABLE)404the endpoint does not exist in the version
ApiVersionException::RETIRED (API_VERSION_RETIRED)410the 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 where the application configures exceptions:

bootstrap/app.php
1use Illuminate\Foundation\Configuration\Exceptions;
2use Pharaonic\Laravel\ApiVersioning\Exceptions\ApiVersionException;
3 
4->withExceptions(function (Exceptions $exceptions) {
5 $exceptions->render(function (ApiVersionException $e) {
6 return response()->json(['error' => $e->errorCode()], $e->getStatusCode(), $e->getHeaders());
7 });
8})

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:

Terminal
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.

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.
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 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:

Terminal
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:

Terminal
php artisan boost:update

#What the Agent Learns

ResourceLoadedCovers
Guideline (resources/boost/guidelines/core.blade.php)In every sessionDeclaring versions, version groups and route constraints, controllers per version, $request->apiVersion() and whenVersion()
Skill api-versioning-developmentWhen the agent works on versioned endpointsEvery public method, the configuration, resolvers, versioned resource classes, lifecycle headers, errors, pitfalls and testing
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)

MethodDescriptionReturns
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 registrarVersionedRouteRegistrar|null
Route::versions(string|array ...$versions)A group available in the listed versionsVersionedRouteRegistrar
Route::sinceVersion(string $version)A group available from a version onVersionedRouteRegistrar
Route::untilVersion(string $version)A group available up to a versionVersionedRouteRegistrar

#VersionedRouteRegistrar

MethodDescriptionReturns
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 filevoid
get(), post(), put(), patch(), delete(), options(), any(), match()Register one routeIlluminate\Routing\Route

#Route (on a route)

MethodDescriptionReturns
->versions(string|array ...$versions)Available in the listed versionsRoute
->sinceVersion(string $version)Available from a version onRoute
->untilVersion(string $version)Available up to a versionRoute
->controllers(array $controllers, bool $fallback = false)A controller per version; with $fallback, unmapped versions use the route's own controllerRoute

#Request

MethodDescriptionReturns
$request->apiVersion()The resolved version, null when the route is not versionedVersion|null

#JsonResource

MethodDescriptionReturns
$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 MissingValuemixed

#Version

MethodDescriptionReturns
name()The version name; also (string) $versionstring
is($version)Same versionbool
atLeast($version) / atMost($version)Same or later / same or earlierbool
after($version) / before($version)Later / earlierbool

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

#VersionRegistry

Resolve it from the container.

MethodDescriptionReturns
all()Declared versions, oldest firstlist<string>
has(string $name)Whether a version is declaredbool
get(string $name)A versionVersion
default()The default versionVersion|null
compare($a, $b)Negative, zero or positive by declared orderint
status($version)active, deprecated, sunset-announced or retiredstring

#VersionedResources

MethodDescriptionReturns
register(string $resource, array $versions, ?string $fallback = null)Map a resource to classes per versionvoid
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 classJsonResource
collection(string $resource, mixed $value)Laravel's collection of the resolved classAnonymousResourceCollection

#Other

NameDescription
Concerns\InteractsWithApiVersionTrait providing the same whenVersion(), for resources written for Laravel 8 and earlier
Contracts\VersionResolverresolve(Request $request): ?string for custom resolvers
Exceptions\ApiVersionExceptionerrorCode() 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.

routes/api.php
1use App\Http\Controllers\TeamController;
2use App\Http\Controllers\UserController;
3use App\Http\Controllers\UserV2Controller;
4 
5Route::sinceVersion('v1')->group(function () {
6 Route::get('users', [UserController::class, 'index']);
7 Route::get('users/{user}', [UserController::class, 'show'])->controllers([
8 'v1' => [UserController::class, 'show'],
9 'v2' => [UserV2Controller::class, 'show'],
10 ], true);
11});
12 
13Route::sinceVersion('v2')->group(function () {
14 Route::apiResource('teams', TeamController::class);
15});

#2. Versions in the URL

config/pharaonic/api-versioning.php
1'versions' => ['v1', 'v2'],
2'resolvers' => ['path'],
3'path' => ['prefix' => '{version}', 'name' => '{version}.'],
routes/api.php
1Route::version('v1', function () {
2 Route::apiResource('users', 'V1\UserController');
3});
4 
5Route::version('v2')->middleware('auth:api')->group(function () {
6 Route::apiResource('users', 'V2\UserController');
7});
8 
9// /api/v1/users → v1.users.index, /api/v2/users → v2.users.index

#3. Adding a Field in v2

app/Http/Resources/OrderResource.php
1public function toArray($request)
2{
3 return [
4 'id' => $this->id,
5 'total' => $this->total,
6 'currency' => $this->whenVersion('>=v2', fn () => $this->currency),
7 'items' => OrderItemResource::collection($this->whenLoaded('items')),
8 ];
9}

#4. Retiring a Version

config/pharaonic/api-versioning.php
1'lifecycle' => [
2 'v1' => ['status' => 'deprecated', 'deprecated_at' => '2026-06-01', 'sunset_at' => '2026-12-31', 'link' => 'https://example.com/v2-migration'],
3],
4// 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.

Contributors

Amazing people who made this package possible

This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel API Versioning!

Moamen Eltouny

@MoamenEltouny

57 contributions

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.

Was this page helpful?

Something wrong or missing? Report it on GitHub .