How can you create wildcard routes on Lumen?

230 views Asked by At

Let's say I have a controller called TeamsController. Controller has following method, that returns all teams user has access to.

public function findAll(Request $request): JsonResponse
{
  //...
}

Then I have bunch of other controllers with the same method. I would like to create a single route, that would work for all controllers, so I would not need to add a line for each controller every time I create a new controller.

I am unable to catch the controller name from URI. This is what I have tried.

$router->group(['middleware' => 'jwt.auth'], function () use ($router) {
    // This works
    //$router->get('teams', 'TeamsController@findAll');
    
    // This just returns TeamsController@findAll string as a response
    $router->get('{resource}', function ($resource) {
        return ucfirst($resource) . 'Controller@findAll';
    });
});
1

There are 1 answers

0
Gert B. On

You return a string instead of calling a controller action: I believe Laravel loads the controllers this way (not tested)

$router->group(['middleware' => 'jwt.auth'], function () use ($router) {
  $router->get('{resource}', function ($resource) {
    $app = app();
    $controller = $app->make('\App\Http\Controllers\'. ucfirst($resource) . 'Controller');
    return $controller->callAction('findAll', $parameters = array());
 });
});

But again, I don't really think it's a good idea.