Home » Php » php – Laravel API versioning folders structure

php – Laravel API versioning folders structure

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am new in api versioning ,so my question is :

1)Is this folder structure true?

/app
  /controllers
    /Api
      /v1
        /UserController.php
      /v2
        /UserController.php

for routes :

Route::group(['prefix' => 'v1'], function () {
  Route::get('user',      'Api\v1\[email protected]');
  Route::get('user/{id}', 'Api\v1\[email protected]');
});

Route::group(['prefix' => 'v2'], function () {
  Route::get('user',      'Api\v2\[email protected]');
  Route::get('user/{id}', 'Api\v2\[email protected]');
});

2)what about folder structure for models and events , should I make model for every version?

How to&Answers:

Your approach is correct for API versioning. To avoid repeating the Api\vN\ prefix before every controller path, you could also do:

Route::group(['prefix' => 'api/v1', 'namespace' => 'Api\v1'], function () {
  Route::get('user',      '[email protected]');
  Route::get('user/{id}', '[email protected]');
});

Route::group(['prefix' => 'api/v2', 'namespace' => 'Api\v2'], function () {
  Route::get('user',      '[email protected]');
  Route::get('user/{id}', '[email protected]');
});

If you don’t want to manage it by yourself you could also use some API library that supports versioning. I successfully used Dingo many times but probably there are some more available.

I don’t think you should version models. They should represent your current database structure and therefore be unique. If you need to make some changes, try to make it backwards-compatible with the API versions you are still maintaining.

Same story for the events, unless they are strongly coupled to your API. In that case, I believe that the best folder structure should be equivalent to the controllers one:

/app
  /Events
    /Api
      /v1
        /ApiEvent.php
      /v2
        /ApiEvent.php
    GenericEvent.php