(Laravel) Quick Tip: Dynamically Route a Controller

When I’m working on a controller, I usually will combine my add/edit methods to help keep my controllers lean and mean. In the other frameworks I used this was generally as easy as adding a route like so

// CodeIgniter
$config['([a-z\_]+)/add'] = '$1/edit';
// Kohana
Route::set('manage', '<controller>/add', array(
'controller' => '[a-z0-9\_]+'
->defaults(array('action' => 'edit'));
// CakePHP
Router::connect('/:controller/add', array('action' => 'edit'));

However, in working with Laravel it just wasn’t that easy, probably because Laravel expects all controllers to be defined so it can do a super-quick search for them at runtime. I came up with a (hacky) solution that modified the core controller class (while I really enjoy working with Laravel the fact is its core just isn’t terribly extensible). I really hate modifying core classes.

And then – the lightbulb went on! I remembered that a) I can use anonymous functions for routing and b) Controller::call can be used anywhere.

NOTE: For now this only appears to work in subfolder controllers. It seems (from examining the generated route list) that any route that *starts* with a wildcard (eg, (:any)) will be moved to the bottom of the list. For me, this wasn’t a big deal; my add/edit classes are almost always in admin folders anyway.

Route::any('admin/(:any)/add/(:any?)', function($controller,$params=null) {
return Controller::call('admin.'.$controller.'@edit', (array) $params);

There you have it! 🙂

Leave a comment


  1. I’ll immediately clutch your rss as I can’t in finding your e-mail subscription hyperlink or newsletter service.
    Do you have any? Kindly permit me recognize so that I may just
    subscribe. Thanks.

  2. I use it like this

    Route::get('admin/(:any)/(:any?)/(:all?)', function($controller, $method = 'index', $args = null) {
    	return Controller::call("mod_{$controller}::{$controller}@$method",  array($args));

    Note, i use :all so i can have dynamic segments 😀

  1. Comparing Laravel, CodeIgniter, & CakePHP « A Nerdy Mom!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: