skip to Main Content

I want to dynamically invoke a bespoke controller based on a variable provided by the request.

Route::get('/{variable}', function($variable){
// Invoke controller, something like this...:
//{$variable}Controller@index
})

How?

2

Answers


  1. Controller are not really meant to be used like that. Why not create any other class to handle your logic?

    When you have logic that might be duplicated between controllers, the solution is never to use one controller inside another, the solution is to extract that logic to a new class that can be used in both places.

    Example create a register action class (any php class works)

    namespace AppActions;
    
    class RegisterAction
    {
      public static function handle()
      {
        ...
      }
    }
    

    Now based on your $variable, link your variable to your implementation. You can use a match, switch statement, factory class or any other method.

    Route::get('/{variable}', function($variable){
      $action = match($variable) {
        "register" => AppActionsRegisterAction::class,
        ...
      };
      
      return $action::handle();
    })
    
    Login or Signup to reply.
  2. You can do something like this. Not a perfect solution but it works

    Route::get('/{variable}', function($variable){
        $className = "AppHttpControllers\". $variable ."Controller";
        echo $className::index();
    });
    

    In this example all Controllers need to have same namespace

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search