简体   繁体   中英

Pass dynamic controller in route in laravel

Route::get($PageController[2], [RollsController::class , $PageController[2]]);

Hi coder, I want to pass dynamic class instead of RollsController .

Suppose that I have $controller_name = 'RollsController'; So I want to pass this variable in route instead of RollsController::class

How to achieve them?

I tried like following, but it gives me an error. Thanks in advance.

Route::get($PageController[2], [$controller_name::class , $PageController[2]]); //I want this type of route with dynamic controller. 

You can use ::class only on object

$controller_name = RollsController::class;
Route::get($PageController[2], [(new $controller_name)::class, $PageController[2]]);  

or using reflection

$controller_name = RollsController::class;
try {
    $oClass = new ReflectionClass($controller_name);
    Route::get($PageController[2], [$oClass::class, $PageController[2]]);
} catch (ReflectionException $e) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM