Middleware: checking url with parameter

In my middleware file, I have code which looks like this:

   $uri = $request->getUri ()->getPath ();
    if ($uri[0] != '/') {
        $uri = "/$uri";
    switch ($uri) {
        case '/':
        case '/login':
        case '/logout':
        case '/register':
        case '/helpdesk':
        case '/profile:
            // check if user is logged in, etc.

Now this is all fine and well, but the /helpdesk route can receive a parameter to open a particular helpdesk ticked. When this happens, of course my check (/helpdesk) does not match the received URI anymore.


  1. Is there a smart way to handle this given an URI?
  2. Should I just switch using the route names for this verification (since the route name for the route which matches “/helpdesk/1234” doesn’t encode the parameter and thus will match my check)?

Thanks for any pointers

Why not skip the check and just add the middleware to the routes needed instead of the entire application?

Because I’ll be having a ton of routes and the resulting code would probably be pretty cluttered up.

Also, isn’t putting this into middleware the “slim way” of doing things?

Putting the logic as middleware is OK. What I ment is to add the middleware to the routes needed instead of the entire application.


As you can read there are 2 levels of middleware: application and route.

If you add the authentication middleware just to the routes that need authentication, you don’t need to check the url.

1 Like

@TheLobos, What @JoeBengalen is suggesting is the way I handle it as well. Apply the middleware to the applicable routes when you define them. All the middleware needs to do is to check if the user is logged in, it doesn’t need to check the route itself.

I will often put various routes into a route group. (You can even do it with an empty route pattern.) Then apply the necessary middleware(s) to the groups.

Thanks, I’ll take a look at that option. Appreciate your suggestions.