Wednesday, May 15, 2013

Laravel 3: Unlimited routing arguments

Problem:
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.

Solution:
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', 
        function(){
            $args = func_get_args();
            if (empty($args)){
                $action = 'index';
            }else{
                $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: