Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dave101ua's avatar

Dynamic controller based on input param

Hello,

I have route like this $router->post('something/{id}', ['uses' => 'MyController@process']); I want that controller name is different based on {id}param. With id I look in db and read some data and based on data type I want to run corresponding controller.

I guess I need to use Middleware where I can do this database operation and define type of controller to be executed but how to execute proper controller then ?

All I see in Middleware examples is that either you do redirect to some URL or return $next($request);

0 likes
4 replies
Snapey's avatar

I would probably accept the id into the single controller, then dispatch a class to handle the request type (strategy pattern I think)

dave101ua's avatar

@Snapey single controller is good for me main question: in single controller, imagine I define via strategy what is the name of controller where to dispatch how to dispatch request to this controller then ?

Snapey's avatar

@dave101ua

It wouldn't be a controller, it would be just a simple class. It could extend Controller if you need access to the standard controller functions

MyController.php

    public function process($id)
    {
		$model = Model::find($id);

         abort_if(! class_exists($model->classname()),404)

         return (new $model->classname)->handle($id);
    } 

Assumes that your model has a classname function that returns a string containing the name of the class to call and that your called class contains a handle method

but this is only an example. You can construct it multiple ways.

Please or to participate in this conversation.