PHPackages                             shahghasiadil/laravel-api-versioning - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. shahghasiadil/laravel-api-versioning

ActiveLibrary[API Development](/categories/api)

shahghasiadil/laravel-api-versioning
====================================

Elegant attribute-based API versioning solution for Laravel applications with built-in deprecation management and version inheritance

v0.0.4(7mo ago)2913.6k↓33.7%4MITPHPPHP ^8.2CI passing

Since Aug 19Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/shahghasiadil/laravel-api-versioning)[ Packagist](https://packagist.org/packages/shahghasiadil/laravel-api-versioning)[ GitHub Sponsors](https://github.com/:vendor_name)[ RSS](/packages/shahghasiadil-laravel-api-versioning/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (14)Versions (11)Used By (0)

Laravel API Versioning
======================

[](#laravel-api-versioning)

[![Latest Version on Packagist](https://camo.githubusercontent.com/894a8f859656ed80ba5484ab9595f2dda6f2c4bbd2d80406b87102e38df91968/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7368616867686173696164696c2f6c61726176656c2d6170692d76657273696f6e696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shahghasiadil/laravel-api-versioning)[![Total Downloads](https://camo.githubusercontent.com/624c23dd4f7c690d4c3418916b69ac12c89b4d636a7c10ea954a79e38a1c719d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7368616867686173696164696c2f6c61726176656c2d6170692d76657273696f6e696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shahghasiadil/laravel-api-versioning)[![License](https://camo.githubusercontent.com/6662126a0271e3eaa91ad158439332f5c22354ed193a3a6bf3e3a76116ef916d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7368616867686173696164696c2f6c61726176656c2d6170692d76657273696f6e696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shahghasiadil/laravel-api-versioning)

Attribute-based API versioning for Laravel, with version detection, deprecation metadata, versioned resources, and route inspection commands.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, or 12

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require shahghasiadil/laravel-api-versioning
```

Publish the config file:

```
php artisan vendor:publish --provider="ShahGhasiAdil\LaravelApiVersioning\ApiVersioningServiceProvider" --tag="config"
```

Quick Start
-----------

[](#quick-start)

### 1. Configure supported versions

[](#1-configure-supported-versions)

Edit `config/api-versioning.php`:

```
return [
    'default_version' => '2.0',
    'supported_versions' => ['1.0', '1.1', '2.0', '2.1'],

    'detection_methods' => [
        'header' => ['enabled' => true, 'header_name' => 'X-API-Version'],
        'query' => ['enabled' => true, 'parameter_name' => 'api-version'],
        'path' => ['enabled' => true, 'prefix' => 'api/v'],
        'media_type' => ['enabled' => false, 'format' => 'application/vnd.api+json;version=%s'],
    ],
];
```

### 2. Apply middleware to API routes

[](#2-apply-middleware-to-api-routes)

`api.version` middleware alias is registered by the package.

```
use Illuminate\Support\Facades\Route;

Route::middleware('api.version')->group(function () {
    Route::apiResource('users', UserController::class);
});
```

### 3. Add version attributes to your controller

[](#3-add-version-attributes-to-your-controller)

```
use ShahGhasiAdil\LaravelApiVersioning\Attributes\ApiVersion;
use ShahGhasiAdil\LaravelApiVersioning\Attributes\Deprecated;
use ShahGhasiAdil\LaravelApiVersioning\Attributes\MapToApiVersion;
use ShahGhasiAdil\LaravelApiVersioning\Traits\HasApiVersionAttributes;

#[ApiVersion(['2.0', '2.1'])]
class UserController extends Controller
{
    use HasApiVersionAttributes;

    public function index(): JsonResponse
    {
        return response()->json([
            'version' => $this->getCurrentApiVersion(),
            'deprecated' => $this->isVersionDeprecated(),
        ]);
    }

    #[MapToApiVersion(['2.1'])]
    public function store(Request $request): JsonResponse
    {
        return response()->json(['message' => 'Created']);
    }

    #[MapToApiVersion(['2.0'])]
    #[Deprecated(message: 'Use store() instead', replacedBy: '2.1', sunsetDate: '2026-12-31')]
    public function create(Request $request): JsonResponse
    {
        return response()->json(['message' => 'Deprecated endpoint']);
    }
}
```

### 4. Call your API with a version

[](#4-call-your-api-with-a-version)

```
# Header
curl -H "X-API-Version: 2.0" https://api.example.com/api/users

# Query string
curl "https://api.example.com/api/users?api-version=2.0"

# Path-based
curl https://api.example.com/api/v2.0/users

# Media type
curl -H "Accept: application/vnd.api+json;version=2.0" https://api.example.com/api/users
```

Features
--------

[](#features)

- Controller and method level attributes (`ApiVersion`, `MapToApiVersion`)
- Version-neutral endpoints (`ApiVersionNeutral`)
- Deprecation metadata (`Deprecated` with message, sunset date, replacement)
- Multiple version detection methods (header, query, path, media type)
- Response headers for active/supported/deprecated versions
- Version-aware resources and resource collections
- Version inheritance and method mapping for resources
- RFC 7807 problem+json error responses for unsupported versions
- Built-in version comparison utilities
- Cache layer for attribute resolution
- Artisan commands for generation, inspection, config and health checks
- Testing base class with version request/assert helpers

Attributes
----------

[](#attributes)

### `ApiVersion`

[](#apiversion)

Use on a controller or method.

```
#[ApiVersion('2.0')]
#[ApiVersion(['1.0', '1.1', '2.0'])]
```

### `MapToApiVersion`

[](#maptoapiversion)

Use on a method to map it to specific versions.

```
#[MapToApiVersion(['2.0', '2.1'])]
```

### `ApiVersionNeutral`

[](#apiversionneutral)

Marks controller/method as version-neutral (available in all supported versions).

```
use ShahGhasiAdil\LaravelApiVersioning\Attributes\ApiVersionNeutral;

#[ApiVersionNeutral]
class HealthController extends Controller
{
    // ...
}
```

### `Deprecated`

[](#deprecated)

Add deprecation metadata to controller/method.

```
#[Deprecated(
    message: 'Use v2 endpoint',
    sunsetDate: '2026-12-31',
    replacedBy: '2.0'
)]
```

Response Headers
----------------

[](#response-headers)

When middleware is active, responses can include:

```
X-API-Version: 2.0
X-API-Supported-Versions: 1.0, 1.1, 2.0, 2.1
X-API-Route-Versions: 2.0, 2.1
X-API-Deprecated: true
X-API-Deprecation-Message: Use store() instead
X-API-Sunset: 2026-12-31
X-API-Replaced-By: 2.1
```

Versioned Resources
-------------------

[](#versioned-resources)

### `VersionedJsonResource`

[](#versionedjsonresource)

Extend `VersionedJsonResource` and implement `toArrayDefault()`. Then optionally add version-specific methods (`toArrayV1`, `toArrayV11`, `toArrayV2`, `toArrayV21`) or custom mappings via config.

```
use Illuminate\Http\Request;
use ShahGhasiAdil\LaravelApiVersioning\Http\Resources\VersionedJsonResource;

class UserResource extends VersionedJsonResource
{
    protected function toArrayV1(Request $request): array
    {
        return ['id' => $this->id, 'name' => $this->name];
    }

    protected function toArrayV2(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }

    protected function toArrayDefault(Request $request): array
    {
        return $this->toArrayV2($request);
    }
}
```

### `VersionedResourceCollection`

[](#versionedresourcecollection)

Extend `VersionedResourceCollection` for version-aware list payloads.

```
use Illuminate\Http\Request;
use ShahGhasiAdil\LaravelApiVersioning\Http\Resources\VersionedResourceCollection;

class UserCollection extends VersionedResourceCollection
{
    protected function toArrayV1(Request $request): array
    {
        return ['data' => $this->collection];
    }

    protected function toArrayV2(Request $request): array
    {
        return [
            'data' => $this->collection,
            'meta' => ['count' => $this->collection->count()],
        ];
    }

    protected function toArrayDefault(Request $request): array
    {
        return $this->toArrayV2($request);
    }
}
```

Version Comparison Helpers
--------------------------

[](#version-comparison-helpers)

In controllers/resources using `HasApiVersionAttributes`:

- `getCurrentApiVersion()`
- `isVersionDeprecated()`
- `getDeprecationMessage()`
- `getSunsetDate()`
- `getReplacedByVersion()`
- `isVersionGreaterThan()`
- `isVersionGreaterThanOrEqual()`
- `isVersionLessThan()`
- `isVersionLessThanOrEqual()`
- `isVersionBetween()`

Direct service usage:

```
use ShahGhasiAdil\LaravelApiVersioning\Services\VersionComparator;

$comparator = app(VersionComparator::class);
$comparator->isGreaterThan('2.0', '1.0');
$comparator->satisfies('2.1', '^2.0');
```

Error Format (RFC 7807)
-----------------------

[](#error-format-rfc-7807)

Unsupported versions return `application/problem+json`:

```
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Unsupported API Version",
  "status": 400,
  "detail": "API version '3.0' is not supported for this endpoint.",
  "requested_version": "3.0",
  "supported_versions": ["1.0", "1.1", "2.0", "2.1"],
  "endpoint_versions": ["2.0", "2.1"]
}
```

Optional `documentation` is included when `api-versioning.documentation.base_url` is set.

Artisan Commands
----------------

[](#artisan-commands)

Generate controller stub with attributes:

```
php artisan make:versioned-controller UserController --api-version=2.0
php artisan make:versioned-controller V1UserController --api-version=1.0 --deprecated --sunset=2026-12-31 --replaced-by=2.0
```

Inspect routes and versions:

```
php artisan api:versions
php artisan api:versions --route=users
php artisan api:versions --api-version=2.0
php artisan api:versions --deprecated
php artisan api:versions --compact
php artisan api:versions --json
```

Check configuration health:

```
php artisan api:version:health
```

Show config overview:

```
php artisan api:version-config --show
php artisan api:version-config --add-version=2.2 --method=toArrayV22
```

Clear attribute cache:

```
php artisan api:cache:clear
```

Testing Helpers
---------------

[](#testing-helpers)

Use `ShahGhasiAdil\LaravelApiVersioning\Testing\ApiVersionTestCase` in package/app tests.

Available helpers include:

- Requests: `getWithVersion`, `getWithVersionQuery`, `postWithVersion`, `putWithVersion`, `deleteWithVersion`
- Assertions: `assertApiVersion`, `assertApiVersionDeprecated`, `assertApiVersionNotDeprecated`, `assertSupportedVersions`, `assertRouteVersions`, `assertDeprecationMessage`, `assertReplacedBy`

Configuration Reference
-----------------------

[](#configuration-reference)

Main file: `config/api-versioning.php`

```
return [
    'default_version' => '1.0',

    'detection_methods' => [
        'header' => [
            'enabled' => true,
            'header_name' => 'X-API-Version',
        ],
        'query' => [
            'enabled' => true,
            'parameter_name' => 'api-version',
        ],
        'path' => [
            'enabled' => true,
            'prefix' => 'api/v',
        ],
        'media_type' => [
            'enabled' => false,
            'format' => 'application/vnd.api+json;version=%s',
        ],
    ],

    'supported_versions' => ['1.0', '1.1', '2.0', '2.1'],

    'version_method_mapping' => [
        '1.0' => 'toArrayV1',
        '1.1' => 'toArrayV11',
        '2.0' => 'toArrayV2',
        '2.1' => 'toArrayV21',
    ],

    'version_inheritance' => [
        '1.1' => '1.0',
        '2.1' => '2.0',
    ],

    'default_method' => 'toArrayDefault',

    'documentation' => [
        'base_url' => env('API_DOCUMENTATION_URL'),
    ],

    'cache' => [
        'enabled' => env('API_VERSIONING_CACHE_ENABLED', true),
        'ttl' => env('API_VERSIONING_CACHE_TTL', 3600),
    ],
];
```

Environment variables:

```
API_DOCUMENTATION_URL=https://docs.example.com/api
API_VERSIONING_CACHE_ENABLED=true
API_VERSIONING_CACHE_TTL=3600
```

Development
-----------

[](#development)

Run tests:

```
composer test
```

Run static analysis:

```
composer analyse
```

Format code:

```
composer format
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover any security-related issues, please email .

Credits
-------

[](#credits)

- [Shahghasi Adil](https://github.com/shahghasiadil)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [LICENSE.md](LICENSE.md) for details.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance79

Regular maintenance activity

Popularity37

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~15 days

Total

4

Last Release

225d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0a0a3bb25b5438613463e20699f30cc02e24a0e57e7d171208e3d19bd6bf7b4a?d=identicon)[shahghasiadil](/maintainers/shahghasiadil)

---

Top Contributors

[![shahghasiadil](https://avatars.githubusercontent.com/u/64509320?v=4)](https://github.com/shahghasiadil "shahghasiadil (70 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

api-deprecationapi-versionapi-version-managementapi-version-managerapi-versioningattribute-based-api-versioninglaravel-apilaravel-api-versioninglaravel-frameworkphp-api-versioningmiddlewareapilaravelversioningattributesREST APIphp8deprecationtype-safetyartisan-commandsjson-resourcesapi-managementbackward-compatibilityversion-managementversion-inheritancesunset-datesapi-lifecycleheader-versioningquery-versioningpath-versioning

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/shahghasiadil-laravel-api-versioning/health.svg)

```
[![Health](https://phpackages.com/badges/shahghasiadil-laravel-api-versioning/health.svg)](https://phpackages.com/packages/shahghasiadil-laravel-api-versioning)
```

###  Alternatives

[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[api-ecosystem-for-laravel/dingo-api

A RESTful API package for the Laravel and Lumen frameworks.

3121.5M10](/packages/api-ecosystem-for-laravel-dingo-api)[grazulex/laravel-apiroute

Complete API versioning lifecycle management for Laravel

1036.0k](/packages/grazulex-laravel-apiroute)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[gdebrauwer/laravel-hateoas

Expose the authorization logic of your REST API using HATEOAS links on your Laravel API resources

17389.4k](/packages/gdebrauwer-laravel-hateoas)[imliam/laravel-throttle-simultaneous-requests

Throttle the current user's requests based on how many requests are currently being executed.

4623.0k](/packages/imliam-laravel-throttle-simultaneous-requests)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
