Laravel 5: How to get list of Parameters in Middle

2019-05-16 16:33发布

How can I retrive list of route parameters in Middleware, tried multiple ways but always end with Error or empty result:

public function handle($request, Closure $next)
{
    $request->route()->parameter('page');           //Call to a member function parameter() on null
    $request->route()->parameters();                //Call to a member function parameters() on null
    Request::capture()->getParameter('page');       //Call to undefined method Illuminate\Http\Request::getParameter()

    Route::getCurrentRoute()->getParameter('page'); //Call to a member function getParameter() on null
    Route::getCurrentRoute()->getParameters();      //Call to a member function getParameters() on null
    Route::getParameter('page');                    //Method getParameter does not exist.
}

Is there a way to get list of parameters in Middleware? thanks,

Update: (add Route)

Route::get('test/{page}', array('uses'=>'test@test'));

Laravel version: 5.1.20

3条回答
劫难
2楼-- · 2019-05-16 16:40

You are getting NULL value because you defined your middleware as global and global middleware run before the route is resolved.

If you need access to route parameters, use your middleware as route middleware in App\Http\Kernel::$routeMiddleware :

protected $routeMiddleware = [
    'my.middleware' => [
        \App\Http\Middleware\MyMiddleware::class,
     ],
];

Proposals to change this behavior have been rejected by the Laravel maintainers due to architectural concerns.

查看更多
beautiful°
3楼-- · 2019-05-16 16:58

Use the request() global helper:

request()->route('page');
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-05-16 16:58
$request->route()->parameters();
查看更多
登录 后发表回答