【问题标题】:Passing arguments to a filter - Laravel 4将参数传递给过滤器 - Laravel 4
【发布时间】:2013-08-17 10:33:54
【问题描述】:

是否可以在过滤器中访问路由参数?

例如我想访问 $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');
    }
...

【问题讨论】:

  • 你可以使用这个$agencyId=Request::segment(2)在过滤器中获取agencyId

标签: php laravel laravel-4


【解决方案1】:

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',而不是在构造函数中详细说明。

【讨论】:

    【解决方案2】:

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

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

    另一种选择是通过Route门面检索参数,当您在路由之外时,这很方便:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-17
      • 2021-12-02
      • 2012-07-29
      • 2015-03-22
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多