Wednesday, May 15, 2013

Laravel 3: Unlimited routing arguments

I was working on a project in Laravel when I realized I really wanted to have 1 route rule for a specific controller but be able to allow a lot of different arguments.

I found that I could use func_get_args() in conjunction with the static Controller::call() method to handle an unlimited number of arguments to the receiving controller method.

Route::any('users/(:any?)/(:any?)/(:any?)', array(
        'as' => 'users', 
            $args = func_get_args();
            if (empty($args)){
                $action = 'index';
                $action = array_shift($args);
            return Controller::call("users@{$action}", $args);

There is one caveat to this solution, and that is that you have to specify all the possible captures in the Route URL rule although extra captures are ignored.

No comments: