Search code examples
phplaravellaravel-5middleware

Passing parameters to middleware in Laravel


Let's say I have a route pointing to middleware;

Route::get("/user/{id}", ['middleware' => 'auth', function ($id) {

}]);

And my middleware code is as follows:

public function handle($request, Closure $next)
{
    return $next($request);
}

If I want to use $id in the middleware, how do I do that?


Solution

  • You can use one of the following method to access the route parameter in a middleware:

    First Method

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

    This method will return an array of all the parameters.

    Second Method

    $request->route('parameter_name');

    Here parameter_name refers to what you called the parameter in the route.