简体   繁体   English

Laravel多个可选参数不起作用

[英]Laravel multiple optional parameter not working

While using following route with 2 optional parameters, 使用以下路线时有2个可选参数,

Route::get('/abc-{abc_id?}/xyz-{xyz_id?}', function($abc_id=0, $xyz_id=0)
    {
        return "\n hello ... World";
    });

For requests 对于请求

/abc-1/xyz-15           - Hello World
/abc-1/xyz              - Hello World

But for 但对于

/abc-/xyz-15           - 404
/abc/xyz-15            - 404

Why first optional parameter not working properly? 为什么第一个可选参数不能正常工作 Is there any alternate solutions? 有没有其他解决方案?

Please note both parameters are in url not as a get attribute 请注意,这两个参数都在url中,而不是get属性

Everything after the first optional parameter must be optional. 第一个可选参数后的所有内容都必须是可选的。 If part of the route after an optional parameter is required, then the parameter becomes required. 如果需要在可选参数之后的路径的一部分,则该参数变为必需。

In your case, since the /xyz- portion of your route is required, and it comes after the first optional parameter, that first optional parameter becomes required. 在您的情况下,由于路径的/xyz-部分是必需的,并且它位于第一个可选参数之后,因此需要第一个可选参数。

One option you have would be to include the id prefix as part of the parameter and use pattern matching to enforce the route format. 您拥有的一个选项是将id前缀作为参数的一部分包含在内,并使用模式匹配来强制执行路由格式。 You would then need to parse the actual id out from the parameter values. 然后,您需要从参数值中解析实际的id。

Route::get('/{abc_id?}/{xyz_id?}', function($abc_id = 0, $xyz_id = 0) {
    $abc_id = substr($abc_id, 4) ?: 0;
    $xyz_id = substr($xyz_id, 4) ?: 0;

    return "\n hello ... World";
})->where([
    'abc_id' => 'abc(-[^/]*)?',
    'xyz_id' => 'xyz(-[^/]*)?'
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM