Ted
Ted

Reputation: 4166

Laravel 5: How to get list of Parameters in Middleware

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

Upvotes: 3

Views: 4292

Answers (3)

Prashant Pokhriyal
Prashant Pokhriyal

Reputation: 3827

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.

Upvotes: 1

Avik Aghajanyan
Avik Aghajanyan

Reputation: 1033

$request->route()->parameters();

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

Use the request() global helper:

request()->route('page');

Upvotes: 0

Related Questions