shaikh saliem
shaikh saliem

Reputation: 11

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. 

Upvotes: 1

Views: 582

Answers (1)

Riccardo Venturini
Riccardo Venturini

Reputation: 478

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) {
}

Upvotes: 1

Related Questions