将参数传递给过滤器 - Laravel 4

时间:2013-08-15 08:49:43

标签: php laravel laravel-4

是否可以访问过滤器中的路径参数?

e.g。我想访问$ agencyId参数:

Route::group(array('prefix' => 'agency'), function()
{

    # Agency Dashboard
    Route::get('{agencyId}', array('as' => 'agency', 'uses' => 'Controllers\Agency\DashboardController@getIndex'));

});

我想在我的过滤器中访问此$ agencyId参数:

Route::filter('agency-auth', function()
{
    // Check if the user is logged in
    if ( ! Sentry::check())
    {
        // Store the current uri in the session
        Session::put('loginRedirect', Request::url());

        // Redirect to the login page
        return Redirect::route('signin');
    }

    // this clearly does not work..?  how do i do this?
    $agencyId = Input::get('agencyId');

    $agency = Sentry::getGroupProvider()->findById($agencyId);

    // Check if the user has access to the admin page
    if ( ! Sentry::getUser()->inGroup($agency))
    {
        // Show the insufficient permissions page
        return App::abort(403);
    }
});

仅供参考我在我的控制器中调用此过滤器:

class AgencyController extends AuthorizedController {

    /**
     * Initializer.
     *
     * @return void
     */
    public function __construct()
    {
        // Apply the admin auth filter
        $this->beforeFilter('agency-auth');
    }
...

2 个答案:

答案 0 :(得分:28)

Input::get只能检索GETPOST(等等)参数。

要获取路线参数,您必须在过滤器中抓取Route对象,如下所示:

Route::filter('agency-auth', function($route) { ... });

获取参数(在过滤器中):

$route->getParameter('agencyId');

(只是为了好玩) 在你的路线

Route::get('{agencyId}', array('as' => 'agency', 'uses' => 'Controllers\Agency\DashboardController@getIndex'));

您可以在参数数组'before' => 'YOUR_FILTER'中使用,而不是在构造函数中详细说明它。

答案 1 :(得分:14)

Laravel 4.1中的方法名称已更改为parameter。例如,在RESTful控制器中:

$this->beforeFilter(function($route, $request) {
    $userId = $route->parameter('users');
});

另一个选择是通过Route外观检索参数,当你在路线之外时这很方便:

$id = Route::input('id');