8

This is my routes.php:

$app->get('/users/{id}/', ['middleware' => 'example', function () {
  return "users";
}]);

This is the handle function in the middleware:

public function handle($request, Closure $next)
{
  // I would like to get the value of the url parameter {id} here

  return $next($request);
}

Is there a way I can get the parameter id from my middleware?

* Edit *

I'm using Lumen 5.1.0.

Andrea
  • 15,900
  • 18
  • 65
  • 84
  • I'm not familiar with Laravel but after a quick look I think you have to use the following method: http://laravel.com/docs/5.0/middleware#terminable-middleware . Could you give us the class definition? So, from which class are you inheriting? – GuyT Jul 07 '15 at 19:33
  • @GuyT I'm not inheriting from any class, I'm following a very simple example as described here: http://lumen.laravel.com/docs/middleware#defining-middleware. My middleware class in named `ExampleMiddleware` and it only have the method above. How the "terminable middleware" you linked can be useful for me? – Andrea Jul 07 '15 at 20:28

3 Answers3

11

There are some conventional ways in Laravel doesn't work on Lumen. And get parameter form URI in middleware is one of them. In Laravel, I just need to call $request->id, it will work like magic. But here in order to get parameter in Lumen, I need to do something like this:

$request->route()[2]['id']
Phi Nguyen
  • 3,046
  • 14
  • 26
  • 1
    I don't know which Laravel version you are using.Could you check this `$request->route()->parameter('id')`? – Phi Nguyen Jul 07 '15 at 16:41
  • 1
    when calling $request->route(), it returns an array which has information about your routes such as which middleware you are using, which paramaters you pass. try `dd($request->route()`, you will see what I mean. Then the last index contains parameters which you passed through the route. – Phi Nguyen Jul 07 '15 at 21:17
2

If the $request value passed in is an instance of Illuminate\Http\Request, which I think it might be, that class has a method called input(), which lets you do exactly that:

enter image description here

You should try this:

$id = $request->input('id');
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0

i think the latest lumen 5.6 official tutorial about middleware is no longer applicable, and out of date.

Allen Wayne
  • 121
  • 6