How to define a Laravel route with a parameter that contains a slash character
I have a similar issue but my URL contains several route parameters :
/test/{param1WithSlash}/{param2}/{param3}
And here is how I managed that case :
Route::get('test/{param1WithSlash}/{param2}/{param3}', function ($param1MayContainsSlash, $param2, $param3) {
$content = "PATH: " . Request::path() . "</br>";
$content .= "PARAM1: $param1WithSlash </br>";
$content .= "PARAM2: $param2 </br>".PHP_EOL;
$content .= "PARAM3: $param3 </br>".PHP_EOL;
return Response::make($content);
})->where('param1MayContainsSlash', '(.*(?:%2F:)?.*)');
Hope it can help.
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 ]
I've already upvoted Pierre's answer, it's correct, but in my opinion is longer than needed, here's a very short for-the-impatient sample route that does the trick:
Route::get('post/{slug}', [PostController::class, 'show'])->where('slug', '[\w\s\-_\/]+');
This is all you need. Indeed, the \/
in the regular expression above(in the where
method) is all you need !
Now for example:
- domain/A ---> "A" will be passed to the
show
method of thePostController
. - domain/A/B ---> "A/B" will be passed to the
show
method of thePostController
. - domain/A/B/C ---> "A/B/C" will be passed to the
show
method of thePostController
. - and so on...
For more samples read this: Laravel Documentation - Regular Expression Constraints
urlencoded slashes do not work in Laravel due to what I consider a bug. https://github.com/laravel/framework/pull/4323 This pull request will resolve that bug.
Update.
Note that the change allows the route to be parsed BEFORE decoding the values in the path.