如何在以下路由中验证{id}大于零?
Route::get('/posts/{id}/show', [PostController::class, 'show'])->whereNumber('id');
在X文档中,您应该能够这样做:
Route::get('/posts/{id}/show', [PostController::class, 'show'])
->where('id', '([1-9]+[0-9]*)');
您可以看到regex适用于number >= 1
: https://regex101.com/r/MFxO2h/2
检查源代码,您可以看到whereNumber
是number >= 0
,这就是0
工作的原因。
正如@TimLewis评论的那样,你也可以使用模型绑定,它会自动尝试检查你想要的模型是否存在,并且在路由上带有参数ID。
在你的情况下,让我们假设{id}
是Post
的ID,所以你的路由将是这样的:
Route::get('/posts/{post}/show', [PostController::class, 'show']);
然后,控制器:
public function show(Request $request, Post $post)
{
// ...
}
如果没有{post}
(id)匹配Post的id,则404
,否则控制器正确执行show
方法。