Skip to content
Advertisement

Accessing route parameters in middleware in Slim 4

I would like to know how I can access route parameter in a middleware in Slim 4.

Provided I define a route with placeholder and attached middleware:

JavaScript

I would like to access value of {userId} from middleware before the controller is inovked:

JavaScript

I know that in Slim 3 we could do it accessing attributes of request object, however, it does not work in Slim 4. The attributes of route object contain the following entries:

  • __routingResults__
  • __route__
  • __basePath__

Non of these seems to contain parameters.

Advertisement

Answer

What you need is documented here. You can create the route context, and the route object itself, using the request object in your middleware. Just keep in mind that you have to add routing middleware for this to work. Here is an example:

JavaScript

Now try visiting /1 or /2 and you see the middleware is aware of the parameter value.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement