Effortlessly manage your Laravel API versions with flexible, header-based versioning control.
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"
This will create a config/api-version.php
file where you can customize options like the default version, headers, version format, and the root namespace for versioned controllers.
Example configuration:
return [
'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',
];
The api.version
middleware is registered automatically. This middleware allows for automatic version detection based on headers or explicit version specification in the route.
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.
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 thev1
namespace.api.version:v2
directs routes to thev2
namespace, ignoring headers.
curl -L -H "Accept: application/vnd.yourapp+v2+json" https://yourapp/api/example
curl -L -H "X-API-Version: 2" https://yourapp/api/example
If the route is explicitly defined as api.version:v2
, no header is needed to access version 2.
Run the package tests:
composer test
Please see CHANGELOG for details on recent updates.
Please see CONTRIBUTING for contribution guidelines.
Please review our security policy for reporting security issues.
The MIT License (MIT). See the License File for details.