Skip to content

Instantly share code, notes, and snippets.

@Shaz3e
Last active July 25, 2024 22:19
Show Gist options
  • Save Shaz3e/58d1c3201f1a0899e7158766f305f541 to your computer and use it in GitHub Desktop.
Save Shaz3e/58d1c3201f1a0899e7158766f305f541 to your computer and use it in GitHub Desktop.
Laravel API Versioning
<?php
// routes/api.php
use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(base_path('routes/api/v1.php'));
Route::prefix('v2')->group(base_path('routes/api/v2.php'));
<?php
// bootstrap/app.php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
api: __DIR__ . '/../routes/api.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
then: function(){
// API V1 Routes
Route::middleware('api')
->prefix('api/v1')
->group(base_path('routes/api/v1.php'));
// API V2 Routes
Route::middleware('api')
->prefix('api/v2')
->group(base_path('routes/api/v2.php'));
}
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
<?php
// routes/api/v1.php
use Illuminate\Support\Facades\Route;
Route::get('/data', function() {
return 'api v1' ;
});
<?php
// routes/api/v2.php
use Illuminate\Support\Facades\Route;
Route::get('/data', function() {
return 'api v2' ;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment