我正在尝试使用Laravel 5.4使用一个可选参数创建一条路线.
I'm trying to create a route with one optional parameter with Laravel 5.4.
路线:
Route::get('/run/{zone?}/id/{id}', 'RunController@show');控制器:
class RunController extends Controller { public function show() { $route = \Route::current(); $zone = $route->parameter('zone') ?: 'default'; $id = $route->parameter('id'); Run::setZone($zone); $run = Run::findOrFail($id); return view('run.show')->with(['run' => $run]); } }URL run/test/id/42的工作原理与预期的一样.
The url run/test/id/42 works like expected.
但是,当我期望与run/default/id/42相同的结果时,使用run/id/42我得到了一个不错的NotFoundHttpException in RouteCollection.php
But with run/id/42 I got a nice NotFoundHttpException in RouteCollection.php when I expect the same result than run/default/id/42
我错过了什么?
推荐答案第一个可选参数之后的所有内容都必须是可选的.如果需要在可选参数之后添加路由的一部分,则该参数成为必需.
Everything after the first optional parameter must be optional. If part of the route after an optional parameter is required, then that parameter becomes required.
在您的情况下,路由的id/{id}部分是非可选的,因此必须在路由的该部分之前添加可选"参数.
In your case, the id/{id} part of the route is non-optional, so the "optional" parameter before that section of the route becomes required.
Laravel的路由实际上建立在Symfony的路由之上,这是Symfony中的一个限制.根据此处的Symfony文档(强调我的意思):
Laravel's routing is actually built on top of Symfony's routing, and this is a restriction in Symfony. According to the Symfony documentation here (emphasis mine):
当然,您可以有多个可选的占位符(例如/blog/{slug}/{page}),,但是可选的占位符之后的所有内容都必须是可选的.例如,/{page}/blog是有效路径,但始终需要页面(即/blog不会与此路由匹配).
Of course, you can have more than one optional placeholder (e.g. /blog/{slug}/{page}), but everything after an optional placeholder must be optional. For example, /{page}/blog is a valid path, but page will always be required (i.e. simply /blog will not match this route).
此外,还需要注意另一件事:
Additionally, another thing to watch out for:
在末尾带有可选参数的路由与带有斜杠的请求不匹配(即,/blog/不匹配,/blog将匹配).
Routes with optional parameters at the end will not match on requests with a trailing slash (i.e. /blog/ will not match, /blog will match).
更多推荐
了解带有可选参数的Laravel路线
发布评论