了解带有可选参数的Laravel路线

编程入门 行业动态 更新时间:2024-10-26 08:21:05
本文介绍了了解带有可选参数的Laravel路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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路线

本文发布于:2023-07-14 22:13:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107317.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   路线   参数   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!