简体   繁体   中英

Laravel - Proper way to support a URL piece that might have a slash in it?

I've defined a route in web.php that looks like this:

Route::delete('/app/charges-for-order/{orderId}', 'AppController@deleteOrderCharges');

It seems to work well apart from when orderId has a forward slash in it. Eg 11/11 .

Naturally my first port of call was to generate the url in the frontend using encodeURIComponent :

/app/charges-for-order/${encodeURIComponent(orderId)} (in javascript)

Which produces the url /app/charges-for-order/11%2F11 , replacing the forward slash with %2F -- however, this is giving me a 404, as if Laravel is still seeing %2F as a forward slash for routing purposes.

How can I allow orderId to have (encoded) forward slashes and still be part of the URL like that? Is there some alternate encoding scheme that Laravel will respect in this context?

Use where() clause in route file. Which allows you to use RegEx in the file.

->where('orderId', '^[0-9/]+$'); # or
->where('orderId', '[0-9/]+'); # this

Read - Regular Expression Constraints

IMPORTANT: Do not use ->where('orderId', '.*') or ->where('orderId', '.') any cost.

Side Note: I'm not debugging the DELETE route works or not, just testing whether you can pass params. As well, if you found extensive RegEx, use it. I used this for testing purposes, but still, it does the job


I tested with http://127.0.0.1:8090/app/charges-for-order/11/11 in my local, and the result was

在此处输入图像描述

I assume you are using Apache as HTTP server? At least Apache is by default decoding %2F behind your back: https://httpd.apache.org/docs/2.4/mod/core.html#allowencodedslashes

Changing this might be a bad idea, so I would suggest you would change your route to match all:

Route::delete('/app/charges-for-order/{orderId}', 'AppController@deleteOrderCharges')
     ->where('orderId', '.+');

I ended up just changing the methods in question to accept query parameters or post data instead, I was having trouble with the other answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM