url-routingslimslim-3fastroute

SlimPHP route with empty parameter fails


I have a route like this

/product/update/{productId}/part/{partId}

If I try to call that with one or more empty parameters, it fails and gives me a HTTP 404 Not Found, for example

https://localhost/product/update//part/xyz123 

I can't make them both optional, because I still want to require the full URL, including /part/.

Is it not possible to pass empty parameters to a route using Slim 3? From what I understand, having multiple consecutive slashes is allowed in a URL path?


Solution

  • You can let parameters match empty strings by explicitly defining the regular expression they will match:

    $app->get('/product/update/{productId:.*}/part/{partId:.*}', function ($request, $response, $args) {                                                                 
        $productId = !empty($args['productId']) ?  $args['productId'] : 'not available';                                                                                 
        $partId = !empty($args['partId']) ?  $args['partId'] : 'not available';                                                                                          
        return (sprintf('Product ID: %s, Part ID: %s', $productId,  $partId));                                                                                       
    });
    
    // /product/update/1/part/2  -> Product ID: 1, Part ID: 2
    // /product/update/1/part/   -> Product ID: 1, Part ID: not available
    // /product/update//part/2   -> Product ID: not available, Part ID: 2