Feb 4, 2013

Laravel: Passing parameters to Controllers and Routers

The basic idea is that you want to pass some parameters to your Laravel router so it can do some preprocessing, and then pass the rest of the parameters to the controller.

To get this happening you need to remember that when registering a route in application/routes.php Laravel captures any wildcards as parameters for the function you are registering. This can either be the controller or a custom function that you are registering. You can also call any action from a controller using the Controller::call() interface.

Putting all this together yields:
Route::get('(:any)/welcome/(:any)', function($client, $action)
{
    print($client . "\n");
    return Controller::call('home@index',array($action));
});

The first line of code is the registration function for Router, and we use the (:any) wildcard to capture almost any alpha-numeric character. The function declaration takes two parameters that Laravel fills with our wildcards (NOTE: Laravel uses positional parameters so the first wildcard will take the first variable, and so on).

The second line just prints out our first positional parameter.

The third line runs Index action of the Home controller, passing our second wildcard as it's parameter.

And that's pretty much it. Simple!

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!