php 如何使用包含斜杠字符的参数定义 Laravel 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21552604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:14:43  来源:igfitidea点击:

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

phplaravel

提问by hserusv

I want to define a route with a parameter that will contain a slash /character like so example.com/view/abc/02where abc/02is the parameter.

我想定义一个带有参数的路由,该参数将包含一个斜杠/字符,例如参数example.com/view/abc/02在哪里abc/02

How can I prevent Laravel from reading the slash as a separator for the next route parameter? Because of that I'm getting a 404 not found errornow.

如何防止 Laravel 读取斜杠作为下一个路由参数的分隔符?正因为如此,我得到了一个404 not found error现在。

回答by Gadoma

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

将下面的全能路线添加到您的底部,routes.php并记住composer dump-autoload之后运行。请注意使用“->where”指定参数的可能内容,使您能够使用包含斜杠的参数。

//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]

此外,这里有关于路由参数的详细 Laravel 文档:[文档]

回答by Artistan

urlencoded slashes do not work in Laravel due to what I consider a bug. https://github.com/laravel/framework/pull/4323This pull request will resolve that bug.

由于我认为是一个错误,urlencoded 斜杠在 Laravel 中不起作用。 https://github.com/laravel/framework/pull/4323此拉取请求将解决该错误。

Update.

更新。

Note that the change allows the route to be parsed BEFORE decoding the values in the path.

请注意,此更改允许在解码路径中的值之前解析路由。

回答by Pierre

I have a similar issue but my URL contains several route parameters :

我有一个类似的问题,但我的 URL 包含几个路由参数:

/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.

希望它能有所帮助。