I know there's a way to create versioned URLs for REST APIs with routes, but what's the best way to organize controllers and controller files? I want to be able to create new versions of APIs, and still keep the old ones running for at least some time.
I ended up using namespaces and directories under app/controllers:
/app
/controllers
/Api
/v1
/UserController.php
/v2
/UserController.php
And in UserController.php files I set the namespace accordingly:
namespace Api\v1;
or
namespace Api\v2;
Then in my routes I did something like this:
Route::group(['prefix' => 'api/v1'], function () {
Route::get('user', 'Api\v1\UserController@index');
Route::get('user/{id}', 'Api\v1\UserController@show');
});
Route::group(['prefix' => 'api/v2'], function () {
Route::get('user', 'Api\v2\UserController@index');
Route::get('user/{id}', 'Api\v2\UserController@show');
});
I'm not positive this is the best solution. However, it has allowed versioning of the controllers in a way that they do not interfere with each other. You could probably do something verify similar with the models if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With