Reputation: 40643
I'm working on exposing an API using one base URL (e.g. https://api.domain.com) and having that URL handle all versions of the API (the API consumer will need to send Accept-Version
in the request header to indicate which version of the API they're trying to use).
How would I manage this approach in Laravel?
I was thinking that I could put all of my controllers, helpers, models, routes, config, etc. in a, say, 1.0.0
folder and use those for version 1 of my API. When I release a new version, maybe I make copies of the original code, put them in a 1.1.0
folder, and make changes there.
If I were to use this folder approach, what would I need to do in the routes to indicate which folder to use? How would my controllers know what models, helpers, config, etc. to use? Feels like this approach could get very messy and convoluted.
Upvotes: 1
Views: 1386
Reputation: 562
In your RouteServiceProvider.php
you can define the routes for the application. Here you can also define the namespace, name prefix, and middleware for the routes. Simply add a new route map for each version of your api. Have the middleware check the version, redirecting if necessary, and set the name prefix/namespace to the correct version directory.
the RouteServiceProvider
would look something like:
protected function mapApi-1-0-0-Routes()
{
Route::middleware(['api', 'version'])
->name('1.0.0.')
->namespace('1.0.0')
->group(base_path('routes/api.php'));
}
then your middleware
would look something like
public function handle($request, Closure $next)
{
switch ($request->version) {
case "1.0.0":
$route = $request->version.$request->route()->getName();
break;
// more versions
return redirect()->route($route)->with($request);
}
I haven't tested this.
Route group name prefixes: https://laravel.com/docs/7.x/routing#route-group-name-prefixes
Route namespaces: https://laravel.com/docs/7.x/routing#route-group-namespaces
Redirecting named routes: https://laravel.com/docs/7.x/redirects#redirecting-named-routes
Global middleware: https://laravel.com/docs/7.x/middleware#global-middleware
Writing service providers: https://laravel.com/docs/7.x/providers#writing-service-providers
Upvotes: 1