Francis Lewis
Francis Lewis

Reputation: 8980

Calling controllers dynamically

I'm attempting to create dynamic routing in Laravel for my controllers - I know this can be done in Kohana, but I've been unsuccessful trying to get it working with Laravel.

This is what I have right now:

Route::get('/{controller}/{action?}/{id?}'...

So I would like to call controller/method($id) with that.

Ideally this is what I would like to do:

Route::get('/{controller}/{action?}/{id?}', $controller . '@' . $action);

And have it dynamically call $controller::$action.

I've tried doing this:

Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
    $controller = new $controller();
    $controller->$action();
});

But I get an error message: Class Controller does not exist. So it appears that Laravel is not including all the necessary files when the controller extends the BaseController.

If I use $controller::$action() it tells me I can't call a non-static function statically.

Any ideas for how to make this work?

Upvotes: 1

Views: 1791

Answers (2)

Francis Lewis
Francis Lewis

Reputation: 8980

After reading that Laravel doesn’t support this anymore, I came up with this solution:

$uri = $_SERVER['REQUEST_URI'];
$results = array();
preg_match('#^\/(\w+)?\/?(\w+)?\/?(\w+)?\/?#', $_SERVER['REQUEST_URI'], $results);

// set the default controller to landing
$controller = (empty($results[1])) ? 'landing' : $results[1];

// set the default method to index
$method = (empty($results[2])) ? 'index' : $results[2];

Route::get('{controller?}/{action?}/{id?}', $controller . '@' . $method);

// now we just need to catch and process the error if no controller@method exists.

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220026

You can auto register all controllers in one fell swoop:

Route::controller( Controller::detect() );

If you're using Laravel 4 (as your tag implies), you can't use Controller::detect() anymore. You'll have to manually register all the controllers you want to use.

Upvotes: 1

Related Questions