To organize your API versions in separate folders and ensure that they can be deployed independently, follow these steps:
- Create a new folder named
v1
inside theapp/Http/Controllers/Api
directory. This folder will contain the controllers for API version 1. - Move the existing
UserController
into thev1
Folder and update its namespace accordingly:
namespace App\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
// Logic for API version 1
}
}
- When you need to create a new version of the API, create another folder named
v2
inside theapp/Http/Controllers/Api
directory. Copy the necessary controllers from thev1
folder to thev2
Folder and update their namespaces and logic as needed. For example:
namespace App\Http\Controllers\Api\v2;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
// Logic for API version 2
}
}
- Now, define your routes in the
routes/api.php
File by creating separate route groups for each API version, specifying the folder as a namespace and the version number in the URI:
use Illuminate\Support\Facades\Route;
// API version 1 routes
Route::prefix('v1')->namespace('Api\v1')->group(function () {
Route::get('users', 'UserController@index');
});
// API version 2 routes
Route::prefix('v2')->namespace('Api\v2')->group(function () {
Route::get('users', 'UserController@index');
});
With this setup, your API endpoints will have version numbers in the URI, such as /v1/users
and /v2/users
. The corresponding controllers for each version are located in separate folders, allowing you to manage and deploy them independently.
Remember to update your RouteServiceProvider’s mapApiRoutes()
method in app/Providers/RouteServiceProvider.php
to load the api.php
file:
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
By organizing your API versions in separate folders and using Laravel’s routing system, you can maintain and deploy different versions of your API independently without merging them into new code.