'How to URL encode a URI route parameter in Laravel
I have a URI I need to pass inside a route to a controller. How do I handle this, or more specifically, how can I pass a string that would typically need to be URL encoded first? Could this be Howhandledy, a regular expression constraint in the route?
String to pass
itm:n#_123445
Route
Route::get('getChildren/{uri}', 'ChildrenController@getChildren');
Solution 1:[1]
I would recommend updating your table schema to create a unique id for each uri in the DB, if it does not already have one. Instead of passing the full uri as a parameter, you would pass the id instead.
Solution 2:[2]
First off,
If you are using this specific format, the browser will understand the # as a reference to an anchor in the page - just like this example: https://laravel.com/docs/7.x/packages#views
and won't pass the number to the backend - as you mention you most likely will have to encode the URL before sending it
Now if you are sure that the backend can receive this format, I would do a preg_match in a middleware (if this format is recurrent) or directly in the controller to extract the numerical id.
preg_match('/itm:n#_(\d*)/', $uri , $matches);
$id = matches[0]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mchljams |
| Solution 2 | Christophe Hubert |
