Laravel 路由:如何将参数传递给控制器​​(不是通过 URL)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25268985/
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-09-14 09:56:19  来源:igfitidea点击:

Laravel routing: how to pass parameter to controller (not via URL)?

phplaravellaravel-4controllerrouting

提问by Andrew Vershinin

I have two routes: A/{param}/Cand B/{param}/C. Also I have a controller with method:

我有两条路线:A/{param}/CB/{param}/C。我还有一个带有方法的控制器:

public function index($param, $param1 = false)
{
    //...
}

In case of A/{param}/CI pass only one parameter - one specified in URL, and the function uses the default for second one. In case of the second route, I want to pass trueas second parameter. Since it isn't specified in URL, how to pass it to the function?

如果A/{param}/C我只传递一个参数 - 在 URL 中指定的一个,并且该函数使用第二个的默认值。在第二条路线的情况下,我想true作为第二个参数传递。由于没有在 URL 中指定,如何将其传递给函数?

回答by c-griffin

If i understand you correctly, without using $_POST, you won't be able to pass a parameter without be being somewhere in the URI (outside of setting a session variable, which i wouldn't advise)

如果我理解正确,如果不使用 $_POST,您将无法传递参数而不位于 URI 中的某处(设置会话变量之外,我不建议这样做)

Another option may be to pass it as a query string parameter. It will still be in the url, but won't necessarily be caught in the route pattern

另一种选择可能是将其作为查询字符串参数传递。它仍然会在 url 中,但不一定会被捕获在路由模式中

URLs:

网址:

A/{param}/C
B/{param}/C?param1=true

--
Controller:

--
控制器:

public function index($param)
{

   $param1 = Request::query('param1'); // if not present false, if present, {value}

}

--

——

Alternatively, if you'd like a friendly URL, you can place a question mark after your second parameter, indicating that it may or may not exist. This will match both of the below URLs

或者,如果您想要一个友好的 URL,您可以在第二个参数后放置一个问号,表明它可能存在也可能不存在。这将匹配以下两个 URL

URL:

网址:

A/{param}/C
B/{param}/C/true

Route:

路线:

Route::get('B/{param}/C/{param1?}', 'YourController@index');

Controller:

控制器:

public function index($param, $param1 = false)
{
   //
}