有没有办法在路由中间添加一个可选参数?

示例路由:

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

我试过这个,但不管用:

get('things/{id?}/entities', 'MyController@doSomething');

我知道我能做到.

get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');

... 但我的问题是:Can I add an optional parameter in the middle of a route?

推荐答案

不需要.可选参数需要转到路由的末尾,否则路由将不知道如何将URL与路由匹配.您已经实施的是正确的方法:

get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');

You could try doing it with one route:

get('things/{id}/entities', 'MyController@doSomething');

如果你想获取所有东西的实体,就通过* or 0,但我称之为黑客.

There are some other hacks that could allow you to use one route for that, but it will increase the complexity of your code and it's really not worth it.

Laravel相关问答推荐

从8.0更新到10.0后,图像不再上传到存储

子目录中具有Vue实例的Laravel不起作用

AJAX响应中未定义的全名

Laravel 数据未传递到下拉框

vagrant会损坏你的电脑. | macOS v12(蒙特雷)#13132

如何为 CMP 横幅安装谷歌同意脚本?

Eloquent的条件过滤器

集成测试模拟外观与注入模拟

上传时Laravel正在旋转图像

调用未定义函数 Illuminate\Encryption\openssl_decrypt()

Laravel 扩展验证自定义消息

从 sqlite DB 登录 Laravel,得到PDOException 找不到驱动程序

未找到列:1054 未知列 laravel

Laravel 字符串验证以允许空字符串

Class类 App\Http\Controllers\Auth\Request 不存在.

Elastic search全文与mysql全文?

登录后 DevTools 无法解析 SourceMap 错误将重定向到该 js 文件

如何在不要求用户登录 Laravel 的情况下验证Electron邮件

如何使用 Postman 处理 Laravel $_POST 请求

如何从 laravel 5.1 中数据库表的 created_at 属性中 Select 年份和月份?