SlimPHP route with empty parameter fails

192 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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