How to Define a Laravel Route with a Parameter That Contains a Slash Character

How to define a Laravel route with a parameter that contains a slash character

Add the below catch-all route to the bottom of your routes.php and remember to run composer dump-autoload afterwards. Notice the use of "->where" that specifies the possible content of params, enabling you to use a param containing a slash.

//routes.php
Route::get('view/{slashData?}', 'ExampleController@getData')
->where('slashData', '(.*)');

And than in your controller you just handle the data as you'd normally do (like it didnt contain the slash).

//controller 
class ExampleController extends BaseController {

public function getData($slashData = null)
{
if($slashData)
{
//do stuff
}
}

}

This should work for you.

Additionally, here you have detailed Laravel docs on route parameters: [ docs ]

Passing \ and / in variable via Laravel Route

As you can see from the comments on the original question, the variable I was trying to pass in the URL was the result of a prior API call which I was using json_encode on. json_encode will automatically try and escape forward slashes, hence the additional \ being added to the variable. I added a JSON_UNESCAPED_SLASHES flag to the original call and voila, everything is working as expected.

How to pass forward slash (%2F) in laravel 5 url with addition get parrameters

Including an encoded slash (%2F) in the path component of a URL is not a good idea. The HTTP RFC says that this sequence should be "equivalent" to a real slash:

Characters other than those in the "reserved" and "unsafe" sets (see
RFC 2396 [42]) are equivalent to their ""%" HEX HEX" encoding.

In practice, the handling of these URLs is inconsistent. Some web servers (and even some browsers!) will treat %2F as equivalent to a real slash, some will treat it differently, and some tools, including some web application firewalls and proxies, will simply reject URLs which contain such a sequence.

If you need to include user input like this in a URL, you should probably put it in a query string (/search/?q=search+with+%2f+slash).

Slim 3 - Slash as a part of route parameter

Route placeholders:

For “Unlimited” optional parameters, you can do this:

$app->get('/hello[/{params:.*}]', function ($request, $response, $args) {
$params = explode('/', $request->getAttribute('params'));

// $params is an array of all the optional segments
});


Related Topics



Leave a reply



Submit