从路由到过滤器的 Laravel 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20790922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:48:37  来源:igfitidea点击:

Laravel Pass Parameter from Route to Filter

phproutinglaravellaravel-4mamp

提问by 735Tesla

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

我正在使用 Laravel 框架。如果我有以下路线:

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"?

如何将参数传递给过滤器,以便在访问 /test/foobar 时我会看到一个页面:“值是 foobar”?

回答by Damien Pirsy

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

上面的例子取自文档:http: //laravel.com/docs/routing#route-filters

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

一旦你进入闭包,你就可以从以下参数中获取参数$route

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



或者,我相信您可以只获取您需要的段(未测试但应该可以工作):

Route::filter('test_filter', function() {
    $param = Request::segment(1);
    return "The value is $param";
});