philiprehberger/laravel-api-versioning

Laravel middleware for API versioning with multi-source resolution from headers, Accept vendor types, and URL path segments.

Maintainers

Package info

github.com/philiprehberger/laravel-api-versioning

pkg:composer/philiprehberger/laravel-api-versioning

Statistics

Installs: 16

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.0.4 2026-03-17 21:36 UTC

This package is auto-updated.

Last update: 2026-03-17 21:38:41 UTC


README

Tests Latest Version on Packagist License

Laravel middleware for API versioning with multi-source resolution from headers, Accept vendor types, and URL path segments.

Requirements

  • PHP 8.2+
  • Laravel 11 or 12

Installation

composer require philiprehberger/laravel-api-versioning

Laravel's package auto-discovery registers the service provider automatically.

Publish the config file:

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

This creates config/api-versioning.php.

Usage

Configuration

// config/api-versioning.php

return [
    'supported_versions'  => ['v1', 'v2'],
    'default_version'     => 'v1',
    'latest_version'      => 'v2',
    'deprecated_versions' => [],
    'vendor_name'         => 'myapp',
    'header'              => 'X-API-Version',
    'response_headers'    => true,
];

Registering the Middleware

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'api.version' => \PhilipRehberger\ApiVersioning\ApiVersion::class,
    ]);
})
Route::middleware('api.version')->group(function () {
    // ...
});

Accessing the Current Version

use PhilipRehberger\ApiVersioning\ApiVersion;

$version = ApiVersion::current($request); // e.g. 'v2'

Version Resolution Priority

  1. X-API-Version request header
  2. Accept header vendor type: application/vnd.{vendor_name}.{version}+json
  3. URL path segment: /api/{version}/...
  4. Configured default version

API

Method / Concept Description
ApiVersion::current(Request $request) Get the resolved API version for the current request
ApiVersion middleware Resolves version, sets request attribute, adds response headers
X-API-Version response header The resolved version for each request
X-API-Deprecated response header true / false — whether this version is deprecated

Response Headers

Header Values Meaning
X-API-Version v1, v2, ... The resolved version for this request
X-API-Deprecated true / false Whether this version is deprecated

Unsupported Version Response (400)

{
    "error": {
        "code": "unsupported_api_version",
        "message": "API version 'v99' is not supported.",
        "supported_versions": ["v1", "v2"]
    }
}

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

License

MIT