How can I validate {id} to be greater than zero in the following route?
Route::get('/posts/{id}/show', [PostController::class, 'show'])->whereNumber('id');
CodePudding user response:
Following the Laravel 9.x documentation, you should be able to do this:
Route::get('/posts/{id}/show', [PostController::class, 'show'])
->where('id', '([1-9] [0-9]*)');
You can see that regex works for number >= 1
: https://regex101.com/r/MFxO2h/2
Checking the source code, you can see that whereNumber
is number >= 0
, that is why 0
works.
As @TimLewis commented, you can also use Model Binding, it will automatically try to check if a model you want exists with the parameter ID on the route.
In your case, let's assume {id}
is a Post
's ID, so your Route would be like this:
Route::get('/posts/{post}/show', [PostController::class, 'show']);
Then, your controller:
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
.