我可以在Laravel中的Route::组中添加一个参数,但在调度到Laravel的路由之前将其删除吗


Can I add a parameter to a Route::group in Laravel but remove it before dispatching to a route in Laravel?

我正在使用Laravel 4创建按每个客户的accountname命名的API。每个客户都有自己相同的数据库。所以Foocorp应该调用如下的api:

http://api.example.com/Foocorp/users/5

Barcorp api调用看起来像这个

http://api.example.com/Barcorp/users/5

出于业务/品牌原因,我必须在URL中包含帐户名,因此我无法从URL路由中删除此参数。

这是一个过滤器,我试图从路由中提取帐户名,验证它是活动的,并指向他们的数据库。我希望删除accountname参数,这样我就可以编写所有控制器函数,使其不包含所有控制器函数的$accountname参数。

Route::filter('accountverification', function()
{
    $route = Route::getCurrentRoute();
    $params = $route->getParameters();
    $accountName = $params['accountname'];
    // verify account with this name exists and set up DB connection to point to their database
    // ...
    unset($params['accountname']);
    $route->setParameters($params);
});

这是我使用过滤器的路由组:

Route::group(array('prefix' => '{accountname}', 'before' => 'accountverification'), function() {
    Route::get('users/{id}', 'UsersController@getShow')
        ->where(array('id' => '[0-9]+'));
});

问题是,当调用控制器/函数时,删除过滤器中的参数没有任何效果。在UsersController::getShow函数中,第一个参数始终是组前缀中的accountname

有没有一种方法可以在我的所有路由中包含一个变量/参数,我可以在发送请求之前对其进行处理,而不会将其传递给函数?

可以。使用路由函数:forgetParameter($parameter)删除控制器上参数中包含的参数。此功能在laravel 4.1或更高版本中可用。例如:

Route::filter('accountverification', function(Route $route)
{
    $params = $route->getParameters();
    $accountName = $params['accountname'];
// verify account with this name exists and set up DB connection to point to their database
// ...
    $route->forgetParameter('accountname');
});

例如,我用它来忘记路由中的locale参数,这样它就不会作为参数包含在路由组内的每个控制器方法中。

http://laravel.com/api/4.2/Illuminate/Routing/Route.html#method_forgetParameter

如果这个链接断了,请在以后留下评论,因为我会在必要时更新。

编辑

在Laravel 5中,您也可以使用中间件来实现这一点,因为路由过滤器会贬值。

这不是使用过滤器的正确方法。事实上,如果您定义了一个过滤器"accountname",那么这就是过滤器的名称——但您使用的是"accountverification"。

您应该做的是,在UsersController构造函数中,检查帐户名称。您的路由前缀必须是已知值。