Search code examples
laravelrouteslaravel-5.3middlewareapi-versioning

Laravel 5.3 API Versioning


I am trying to get api versioning in place for an API I am working on, I found this post that explained how to do it using middleware and replacing a string in the route itself. Basically specifying routes like this.

Route::group(['middleware' => ['api-version']], function() {
  Route::get('/endoint', ['uses' => '{api-namespace}\EndpointController@endpoint']);
});

However, when I attempt this I get the following error

Class App\Http\Controllers\{api-namespace}\EndpointController does not exist

It would appear that the container is verifying the existence of route controller files prior to running the middleware which does the replacing. I have added the middleware to the $routeMiddleware in the Http Kernel file.

How can I accomplish this before it checks for the existence of the file?

I thought about adding this to the applications global middleware but I do not want this to run on web only on api calls


Solution

  • Create a different file for next version of API has some downside. You have to create all the routes from version 1

    and in my case version 2 was just some changes to 3 requests. that was the time I felt we need a fallback for this kind of operation.

    then I created a simple Laravel package to support Laravel API versioning it adds fallback functionality to routes. I personally needed this long ago but didn't realize it will be achieved with such a tiny package.

    https://github.com/mbpcoder/laravel-api-versioning