0

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';
    });
});
Firze
  • 3,939
  • 6
  • 48
  • 61
  • 2
    First of all, that sounds like a bad idea. Routes are (and should be) stored in the cache, so I'm not sure that would even work. Your code returns a string, so it's normal that it shows the string as response. the controller function is never called. – Gert B. Sep 15 '21 at 09:12
  • You are going through a lot of time and effort to save you adding one line every time a new resource is added to your API which I am guessing is not frequent. Do you really find this to be a good use of your time? – apokryfos Sep 15 '21 at 09:23
  • @GertB. So they would not be cached, if using Closures? That was what I was also thinking. I guess its better to list all routes then. This is first Lumen / Laravel project in our company so just getting started. Thanks. – Firze Sep 15 '21 at 09:47

1 Answers1

0

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.

Gert B.
  • 2,282
  • 18
  • 21