了解带有可选参数的Laravel路线 [英] Understand Laravel route with optional parameter

查看:121
本文介绍了了解带有可选参数的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路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆