Laravel API: url 在 api.php 文件中匹配

Laravel API: url matching in api.php file

我正在用 Laravel 8 创建一个 API,在对不同资源的请求中,路径映射的行为与我预期的不同。

实体是摄像机和警报级别。一个摄像头可以有多个警报级别。

我在 api.php 文件中的路线是:

//get the information of a specific camera. Works fine.
Route::get('cameras/{id}', [CameraController::class, 'getCamera']);

//get (all) alert levels information from all cameras
Route::get('cameras/alert-levels', [AlertLevelController::class, 'getCamerasAlertLevels']);

当我访问这条路线时:

http://www.example.com/api/v1/cameras/alert-levels

这条路线应该与第二条路线匹配,但它却与第一条路线相匹配。

如果我改变路线的顺序,它们会正常工作,但我认为我不必那样做。也就是说,它应该检测到 URI 与第一个路径不匹配并且与第二个路径匹配。

我是不是搞错了?

非常感谢您。

您应该更改 routes.Because 的顺序,既获取请求又匹配第一个请求,以便转到 cameras/{id}

所以我们必须保留动态参数字符串 last.or 否则你可以按照@shaedrich 提到的其他答案。

出于安全原因,通常将 id 作为加密传递,因此它会生成长字符串

Route::get('cameras/alert-levels', [AlertLevelController::class, 'getCamerasAlertLevels']);

Route::get('cameras/{id}', [CameraController::class, 'getCamera']);

我敢打赌,您的 id 是数字,因此您可以使用 parameter constraints 执行以下操作:

//get the information of a specific camera. Works fine.
Route::get('cameras/{id}', [CameraController::class, 'getCamera'])->where('id', '\d+'); // or ->whereNumber();

//get (all) alert levels information from all cameras
Route::get('cameras/alert-levels', [AlertLevelController::class, 'getCamerasAlertLevels'])