Laravel将参数从路由传递到过滤器 [英] Laravel Pass Parameter from Route to Filter

查看:420
本文介绍了Laravel将参数从路由传递到过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel框架. 如果我有以下路线:

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

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

这个过滤器:

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

如何将参数传递给过滤器,以便在访问/test/foobar时得到一个页面,上面写着:值是foobar"?

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

推荐答案

过滤器可以传递参数,例如Route对象或Request:

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

指定过滤器参数

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

以上示例摘自文档: http://laravel.com/docs/routing#路由过滤器

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

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";
});

这篇关于Laravel将参数从路由传递到过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆