18

I am using the laravel framework. If I have the following route:

Route::get('/test/{param}', array('before'=>'test_filter', 'SomeController@anyAction'));

And this filter:

Route::filter('test_filter', function() {
    $param = [Get the parameter from the url];
    return "The value is $param";
});

How can I pass parameters to the filter so that when visiting /test/foobar I would get a page saying: "The value is foobar"?

735Tesla
  • 3,162
  • 4
  • 34
  • 57

1 Answers1

40

Filters can be passed parameters, like the Route object or the Request:

Specifying Filter Parameters

Route::filter('age', function($route, $request, $value)
{
    //
});

Above example is taken from the docs: http://laravel.com/docs/routing#route-filters

Once you're inside the closure, you take the parameter from the $route:

Route::filter('test_filter', function($route) {
    $param = $route->getParameter('param'); // use the key you defined
    return "The value is $param";
});


Alternatively, I believe you can just fetch the segment you need (not tested but should work):
Route::filter('test_filter', function() {
    $param = Request::segment(1);
    return "The value is $param";
});
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
  • What do you mean by "inside the closure"? – 735Tesla Dec 26 '13 at 20:59
  • 6
    Uhm, I'm no english native speaker, so I might not be expressing well...I mean, in the body of the function you pass as second argument of filter; what you're already doing, i.e. , don't pay much attention to my bad wording :) – Damien Pirsy Dec 26 '13 at 21:01
  • Thanks sorry for not getting that in the first place – 735Tesla Dec 26 '13 at 21:03
  • Just what I was looking for. – enchance Oct 03 '14 at 11:01
  • @DamienPirsy - you say "// use the key you defined" - where I have to define the key? I am not able to get value of parameter – Dariux Mar 04 '15 at 07:03
  • Found that it works this way: $route->getParameter('one'); - one means the first parameter after the method name in url. For example example.com/shops-list/index/paramterOne - parameterOne will be the value in this case. What if I don't want it to be in url? – Dariux Mar 04 '15 at 07:07