Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

metalcoder's avatar

API versioning without replicating all routes and controllers

Is there a way to achieve api versioning without having to replicate all routes and controllers for a new version? My idea is to only add the v2 version of the route and controller updated, and having some kind of fallback to v1 for the rest of the routes. Has anyone done anything like that? Thank you so much.

0 likes
2 replies
martinbean's avatar

@metalcoder You’re going to struggle given that routes need the corresponding controller specifying:

Route::apiResource('/v1/users', 'App\Http\Controllers\Api\V1\UserController');

You can’t really say “Use this controller class if it exists, and if not fall back to this other controller. That’s just not how Laravel routes work. Especially given controllers are instantiated when the app is booted.

So unfortunately, if your API design wasn’t great that you need to make a version two, then you also need to create the controllers to handle those v2 endpoints. There’s nothing stopping you from extending the v1 controller classes if there are no changes, though:

namespace App\Http\Controllers\Api\V2;

use App\Http\Controllers\Api\V1\UserController as V1UserController;

class UserController extends V1UserController
{
}
Route::prefix('v1')->group(function () {
    Route::apiResource('users', 'App\Http\Controllers\Api\V1\UserController');
});

Route::prefix('v2')->group(function () {
    Route::apiResource('users', 'App\Http\Controllers\Api\V2\UserController');
});
cwhite's avatar

Yes it is possible...

What we do is have Api\Endpoint\*Controllers controllers (these are in your route files) which has some middleware to process the version number (in payload) / fallback version (if not provided) and uses str_replace to inject the version into the namespace. If the versioned controller/method exists then the endpoint controller calls the versioned controller through the service container.

Please or to participate in this conversation.