Optional parameter in the middle of a route

前端 未结 3 2034
感动是毒
感动是毒 2020-12-03 21:42

Is there any way to add an optional parameter in the middle of a route ?

Example routes:

/things/entities/
/things/1/entities/

I t

3条回答
  •  借酒劲吻你
    2020-12-03 21:55

    Having the optional parameter in the middle of the route definition like that, will only work when the parameter is present. Consider the following:

    • when accessing the path things/1/entities, the id parameter will correctly get the value of 1.
    • when accessing the path things/entities, because Laravel uses regular expressions that match from left to right, the entities part of the path will be considered to be the value of the id parameter (so in this case $id = 'entitites';). This means that the router will not actually be able to match the full route, because the id was matched and it now expects to have a trailing /entities string as well (so the route that would match would need to be things/entities/entities, which is of course not what we're after).

    So you'll have to go with the separate route definition approach.

提交回复
热议问题