如何在以下路線中驗證 {id} 是否大于零?
Route::get('/posts/{id}/show', [PostController::class, 'show'])->whereNumber('id');
uj5u.com熱心網友回復:
按照Laravel 9.x 檔案,你應該能夠做到這一點:
Route::get('/posts/{id}/show', [PostController::class, 'show'])
->where('id', '([1-9] [0-9]*)');
您可以看到正則運算式適用于number >= 1:https ://regex101.com/r/MFxO2h/2
檢查源代碼,你可以看到,這whereNumber就是number >= 0為什么0有效。
正如@TimLewis 評論的那樣,您還可以使用Model Binding,它會自動嘗試檢查路徑上是否存在您想要的模型以及引數 ID。
在您的情況下,我們假設{id}是 aPost的 ID,因此您的 Route 將如下所示:
Route::get('/posts/{post}/show', [PostController::class, 'show']);
然后,你的控制器:
public function show(Request $request, Post $post)
{
// ...
}
If no {post}(id) matches a Post's ID, then 404, else the controller correctly executes the methods show.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534841.html
標籤:PHP拉维验证路由参数
上一篇:LaravelHasManyThrough和BelongsToMany在我的情況下都不起作用。是資料庫結構問題嗎?
