PHPackages                             cleaniquecoders/laravel-api-version - 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. cleaniquecoders/laravel-api-version

ActiveLibrary[API Development](/categories/api)

cleaniquecoders/laravel-api-version
===================================

Effortlessly manage your Laravel API versions with flexible, header-based versioning control.

1.2.1(2mo ago)2679MITPHPPHP ^8.2 | ^8.3 | ^8.4CI passing

Since Oct 25Pushed 6mo agoCompare

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

READMEChangelog (3)Dependencies (26)Versions (4)Used By (0)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c2aa117aa7750d8369058e0cb9d667e2812202b7ac206ca23b5819993cb64a31/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636c65616e69717565636f646572732f6c61726176656c2d6170692d76657273696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cleaniquecoders/laravel-api-version) [![GitHub Tests Action Status](https://camo.githubusercontent.com/a87e1fa51926be4b94d179847b399e61eb04d8b7b5f6e694099585593fe28f87/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636c65616e69717565636f646572732f6c61726176656c2d6170692d76657273696f6e2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/cleaniquecoders/laravel-api-version/actions?query=workflow%3Arun-tests+branch%3Amain) [![GitHub Code Style Action Status](https://camo.githubusercontent.com/56245a52a8b2c8802d62a00bc9a96d6c63ba39599cfec872b06e44ed7d05ef1b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636c65616e69717565636f646572732f6c61726176656c2d6170692d76657273696f6e2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/cleaniquecoders/laravel-api-version/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain) [![PHPStan](https://github.com/cleaniquecoders/laravel-api-version/actions/workflows/phpstan.yml/badge.svg)](https://github.com/cleaniquecoders/laravel-api-version/actions/workflows/phpstan.yml) [![Total Downloads](https://camo.githubusercontent.com/23ff12ba695e7b7bc1d2ee8511c6cf55a08b58457c5f7e76994c119482e04df3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636c65616e69717565636f646572732f6c61726176656c2d6170692d76657273696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cleaniquecoders/laravel-api-version)

Laravel API Version
===================

[](#laravel-api-version)

Effortlessly manage your Laravel API versions with flexible, header-based versioning control, comprehensive validation, deprecation management, and enterprise-ready features.

Features
--------

[](#features)

✨ **Header-based Version Detection** - Automatic version resolution from `Accept` or custom headers 🛡️ **Comprehensive Validation** - Boot-time configuration validation and runtime version validation 📅 **Deprecation Management** - Built-in support for API version deprecation with proper HTTP headers ⚡ **Performance Optimized** - Caching for namespace resolution and configuration 🎯 **Explicit Version Control** - Support for both automatic detection and explicit version specification 🔧 **Enterprise Ready** - Production-quality error handling and monitoring capabilities

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
    - [Configuration](#configuration)
    - [Middleware Setup](#middleware-setup)
    - [Defining Versioned Routes](#defining-versioned-routes)
    - [Example Requests](#example-requests)
- [Advanced Features](#advanced-features)
    - [Version Validation](#version-validation)
    - [Deprecation Management](#deprecation-management)
    - [Version Format Support](#version-format-support)
    - [Controller Namespace Mapping](#controller-namespace-mapping)
    - [Performance Optimizations](#performance-optimizations)
    - [Error Handling](#error-handling)
- [Configuration Reference](#configuration-reference)
- [Testing](#testing)
- [Migration Guide](#migration-guide)
- [Troubleshooting](#troubleshooting)

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

[](#quick-start)

1. **Install the package:**

    ```
    composer require cleaniquecoders/laravel-api-version
    ```
2. **Publish configuration:**

    ```
    php artisan vendor:publish --tag="laravel-api-version-config"
    ```
3. **Set up routes with versioning:**

    ```
    Route::middleware(['api', 'api.version'])->group(function () {
        Route::get('/users', 'UserController@index');
    });
    ```
4. **Create versioned controllers:**

    ```
    app/Http/Controllers/Api/V1/UserController.php
    app/Http/Controllers/Api/V2/UserController.php

    ```
5. **Make requests with version headers:**

    ```
    curl -H "X-API-Version: 2" https://yourapp/api/users
    ```

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

[](#installation)

You can install the package via composer:

```
composer require cleaniquecoders/laravel-api-version
```

You can publish the config file with:

```
php artisan vendor:publish --tag="laravel-api-version-config"
```

Usage
-----

[](#usage)

### Configuration

[](#configuration)

This will create a `config/api-version.php` file where you can customize options like the default version, headers, version format, supported versions, deprecation settings, and the root namespace for versioned controllers.

Example configuration:

```
return [
    // Basic Configuration
    'default_version' => 'v1',
    'use_accept_header' => true,
    'custom_header' => 'X-API-Version',
    'accept_header_pattern' => '/application\/vnd\.\w+\+v(\d+(\.\d+)*)\+json/',
    'root_namespace' => 'App\Http\Controllers\Api',

    // Version Management
    'supported_versions' => [
        'v1', 'v2', 'v3'
    ],

    // Deprecation Management
    'deprecated_versions' => [
        'v1' => [
            'sunset_date' => '2024-12-31',
            'replacement' => 'v2',
            'message' => 'API v1 is deprecated. Please migrate to v2.',
        ],
    ],
];
```

### Key Configuration Options

[](#key-configuration-options)

- **`supported_versions`** - Whitelist of allowed API versions (empty array allows all)
- **`deprecated_versions`** - Configure deprecation warnings with sunset dates and replacement versions
- **Version validation** - Automatic validation of version formats and supported versions
- **Performance caching** - Built-in caching for namespace resolution and configuration

### Middleware Setup

[](#middleware-setup)

The `api.version` middleware is registered automatically. This middleware provides:

- 🔍 **Automatic version detection** from headers or explicit specification
- ✅ **Comprehensive validation** with helpful error messages
- 📊 **Response headers** including `X-API-Version` and deprecation warnings
- 🚀 **Performance optimization** through caching

### Defining Versioned Routes

[](#defining-versioned-routes)

#### Option 1: Header-Based Version Detection

[](#option-1-header-based-version-detection)

To enable automatic version detection from headers, use the `api.version` middleware in your `routes/api.php`:

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

Route::middleware(['api', 'api.version'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Additional routes here
});
```

This setup detects versions from the `Accept` or `X-API-Version` headers, dynamically routing requests to the correct versioned namespace.

#### Option 2: Explicitly Setting the Version

[](#option-2-explicitly-setting-the-version)

You can explicitly define a version for a route or route group by passing the version to the middleware. This approach bypasses header detection.

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

Route::middleware(['api', 'api.version:v1'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Routes for v1
});

Route::middleware(['api', 'api.version:v2'])->group(function () {
    Route::get('/example', 'ExampleController@index');
    // Routes for v2
});
```

In this example:

- `api.version:v1` directs routes in the group to the `v1` namespace.
- `api.version:v2` directs routes to the `v2` namespace, ignoring headers.

### Example Requests

[](#example-requests)

#### Using `Accept` Header

[](#using-accept-header)

```
curl -L -H "Accept: application/vnd.yourapp+v2+json" https://yourapp/api/example
```

#### Using Custom Header (`X-API-Version`)

[](#using-custom-header-x-api-version)

```
curl -L -H "X-API-Version: 2" https://yourapp/api/example
```

#### Explicitly Versioned Route

[](#explicitly-versioned-route)

If the route is explicitly defined as `api.version:v2`, no header is needed to access version 2.

Advanced Features
-----------------

[](#advanced-features)

### Version Validation

[](#version-validation)

The package provides comprehensive version validation:

```
// Automatically validates version format (v1, v2, v1.1, etc.)
// Checks against supported_versions if configured
// Provides clear error messages for invalid versions

// Example error response for invalid version:
{
    "error": "Invalid API version",
    "message": "Unsupported API version: 'v5'. Supported versions: v1, v2, v3",
    "supported_versions": ["v1", "v2", "v3"]
}
```

### Deprecation Management

[](#deprecation-management)

When using deprecated versions, the API automatically adds appropriate headers:

```
HTTP/1.1 200 OK
X-API-Version: v1
Deprecation: true
Sunset: 2024-12-31
Link: ; rel="successor-version"
X-API-Deprecation-Message: API v1 is deprecated. Please migrate to v2.
```

### Version Format Support

[](#version-format-support)

The package supports various version formats:

- `v1`, `v2`, `v3` - Simple versioning
- `v1.1`, `v2.5` - Minor versions
- `v1.0.1` - Patch versions
- Automatic normalization (e.g., `1` becomes `v1`)

### Controller Namespace Mapping

[](#controller-namespace-mapping)

Versions are automatically mapped to controller namespaces:

- `v1` → `App\Http\Controllers\Api\V1`
- `v2.1` → `App\Http\Controllers\Api\V2_1`
- `v3.0.1` → `App\Http\Controllers\Api\V3_0_1`

### Performance Optimizations

[](#performance-optimizations)

- ⚡ **Configuration Caching** - Reduces repeated config() calls
- 🗄️ **Namespace Caching** - Caches namespace resolution results
- 🔄 **Cache Management** - Automatic cache invalidation and testing support

### Error Handling

[](#error-handling)

The package provides robust error handling:

- **Configuration Validation** - Validates config at boot time
- **Runtime Validation** - Validates versions during request processing
- **Clear Error Messages** - Helpful error responses for debugging
- **Exception Types** - Custom exceptions for different error scenarios

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

[](#configuration-reference)

### Complete Configuration Example

[](#complete-configuration-example)

```
return [
    // Required: Default version when none specified
    'default_version' => 'v1',

    // Header Configuration
    'use_accept_header' => true,
    'custom_header' => 'X-API-Version',
    'accept_header_pattern' => '/application\/vnd\.\w+\+v(\d+(\.\d+)*)\+json/',

    // Namespace Configuration
    'root_namespace' => 'App\Http\Controllers\Api',

    // Version Management
    'supported_versions' => [
        'v1', 'v2', 'v3'
    ],

    // Deprecation Configuration
    'deprecated_versions' => [
        'v1' => [
            'sunset_date' => '2024-12-31',        // RFC 7234 Sunset header
            'replacement' => 'v2',                // Replacement version
            'message' => 'API v1 is deprecated.', // Custom message
        ],
        'v2' => [
            'sunset_date' => '2025-06-30',
            'replacement' => 'v3',
            'message' => 'API v2 will be sunset on June 30, 2025.',
        ],
    ],
];
```

Testing
-------

[](#testing)

Run the package tests:

```
composer test
```

Run with coverage:

```
composer test-coverage
```

Run static analysis:

```
composer analyse
```

The package includes comprehensive tests covering:

- ✅ Version resolution and validation
- ✅ Configuration validation
- ✅ Deprecation functionality
- ✅ Performance optimizations
- ✅ Error handling scenarios
- ✅ Middleware integration

Migration Guide
---------------

[](#migration-guide)

### From v1.x to v2.x

[](#from-v1x-to-v2x)

The package maintains backward compatibility, but you can take advantage of new features:

1. **Add version validation** by configuring `supported_versions`
2. **Set up deprecation warnings** using `deprecated_versions`
3. **Update error handling** to catch `InvalidApiVersionException`
4. **Review performance** improvements with built-in caching

### Upgrading Controllers

[](#upgrading-controllers)

No changes required to existing controllers. The enhanced namespace mapping automatically handles:

```
// v1 controllers remain in: App\Http\Controllers\Api\V1
// v2.1 controllers work in: App\Http\Controllers\Api\V2_1
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

**Invalid version format errors:**

```
// ❌ Wrong
'supported_versions' => ['1', '2', 'invalid']

// ✅ Correct
'supported_versions' => ['v1', 'v2', 'v3']
```

**Configuration validation errors:**

- Ensure `default_version` is included in `supported_versions` when specified
- Verify regex patterns in `accept_header_pattern` are valid
- Check that `root_namespace` points to existing namespace

**Performance considerations:**

- Use `supported_versions` to limit valid versions
- Configure appropriate cache TTL for your environment
- Monitor deprecation header overhead for high-traffic APIs

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for details on recent updates.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for contribution guidelines.

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

[](#security-vulnerabilities)

Please review our [security policy](../../security/policy) for reporting security issues.

Credits
-------

[](#credits)

- [Nasrul Hazim Bin Mohamad](https://github.com/nasrulhazim)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). See the [License File](LICENSE.md) for details.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance76

Regular maintenance activity

Popularity21

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~67 days

Total

3

Last Release

64d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b57069d0f4b634f65eccc6e5d5848990e25968d45ec2cf46d626c6a4658f944b?d=identicon)[nasrulhazim.m](/maintainers/nasrulhazim.m)

---

Top Contributors

[![nasrulhazim](https://avatars.githubusercontent.com/u/10341422?v=4)](https://github.com/nasrulhazim "nasrulhazim (36 commits)")

---

Tags

apilaravelphpversionlaravelCleanique Coderslaravel-api-version

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/cleaniquecoders-laravel-api-version/health.svg)

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

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.0k7.8M57](/packages/dedoc-scramble)[scalar/laravel

Render your OpenAPI-based API reference

6183.9k2](/packages/scalar-laravel)[ryangjchandler/bearer

Minimalistic token-based authentication for Laravel API endpoints.

8129.8k](/packages/ryangjchandler-bearer)[combindma/laravel-facebook-pixel

Meta pixel integration for Laravel

4956.9k](/packages/combindma-laravel-facebook-pixel)[stechstudio/laravel-hubspot

A Laravel SDK for the HubSpot CRM Api

2971.0k](/packages/stechstudio-laravel-hubspot)[njoguamos/laravel-plausible

A laravel package for interacting with plausible analytics api.

208.8k](/packages/njoguamos-laravel-plausible)

PHPackages © 2026

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