doulian5857 2015-05-26 06:06
浏览 348
已采纳

Laravel多个可选参数不起作用

While using following route with 2 optional parameters,

Route::get('/abc-{abc_id?}/xyz-{xyz_id?}', function($abc_id=0, $xyz_id=0)
    {
        return "
 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

  • 写回答

1条回答 默认 最新

  • donglikuang8145 2015-05-26 07:32
    关注

    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.

    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. You would then need to parse the actual id out from the parameter values.

    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 "
     hello ... World";
    })->where([
        'abc_id' => 'abc(-[^/]*)?',
        'xyz_id' => 'xyz(-[^/]*)?'
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?