4

I am using Laravel 4 to create APIs namespaced by accountname of each of my customers. Each customer has their own, identical database. So Foocorp should make api calls that look like this:

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

Barcorp api calls look like this

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

I must include the account name in the URL for business/branding reasons, so I cannot eliminate this parameter from the URL routes.

Here is a filter that I was using to attempt to pull out the account name from the route, verify it is active, and point to their database. I hoped to remove the accountname parameter so that I could write all my controller functions to not include an $accountname parameter for all of them.

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

Here's my route group that uses the filter:

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

The problem is that removing the parameter in the filter does not have any effect when controller/function is called. In the UsersController::getShow function the first parameter is always the accountname from the group prefix.

Is there a way for me to include a variable/parameter in all my routes that I can do something with before the request is dispatched, which won't be passed to the function?

4

2 回答 2

4

是的你可以。使用 route 函数: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 中,您也可以使用中间件来执行此操作,因为 Route 过滤器已弃用。

于 2015-03-23T20:20:54.643 回答
0

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

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

于 2013-06-27T21:04:45.897 回答