Carlos Fdev
Carlos Fdev

Reputation: 755

Prefix all the routes in Lumen

Is there a way in Lumen to prefix all of my routes?

The thing is that I'm versioning my API via URI and for every group that I create I have to set the prefix to 'v1/*' like:

$app->group(['prefix' => 'v1/students/', 'namespace' => 'App\Http\Controllers\Students\Data'], function () use ($app) {
    $app->get('/', 'StudentController@get');
    $app->get('/{id}', 'StudentController@getByID');
});

Upvotes: 2

Views: 6199

Answers (2)

nasskalte.juni
nasskalte.juni

Reputation: 433

You could prefix all routes in your /bootstrap/app.php. Currently, there should be something like

# may be slighlty different, since I typed this from memory
$app->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    require __DIR__ . '/../routes/web.php';
});

As you can see, this loads the web.php file and makes the $router variable available. You can rewrite this to load any php file in the routes directory and prefix all those routes via

$app->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    // load all files in routes directory, prefix all of them
    $globalPrefix =  "/v1";
    $router->group(["prefix" => $globalPrefix], function($router) {
        $routes = glob(__DIR__ . '/../routes/*.php');

        foreach ($routes as $route) require $route;
    });
});

As you can see, all required routes are wrapped in $router->group with your application wide route prefix.

Upvotes: 0

patricus
patricus

Reputation: 62348

Apparently, route groups in Lumen do not inherit any settings, which was intentional to keep the router simpler and faster (see comment here).

Your best bet will probably be to create a route group per version, in order to define a base prefix and controller namespace for that version. But, your individual routes inside those route groups will need to be slightly more verbose. Example shown below:

// creates v1/students, v1/students/{id}
$app->group(['prefix' => 'v1', 'namespace' => 'App\Http\Controllers'], function () use ($app) {
    $app->get('students', 'Students\Data\StudentController@get');
    $app->get('students/{id}', 'StudentController@getByID');
});

// creates v2/students, v2/students/{id}, v2/teachers, v2/teachers/{id}
$app->group(['prefix' => 'v2', 'namespace' => 'App\Http\Controllers'], function () use ($app) {
    $app->get('students', 'Students\Data\StudentController@get');
    $app->get('students/{id}', 'Students\Data\StudentController@getByID');

    $app->get('teachers', 'Teachers\Data\TeacherController@get');
    $app->get('teachers/{id}', 'Teachers\Data\TeacherController@getByID');
});

Upvotes: 4

Related Questions