How can I validate {id} to be greater than zero in the following route?
Route::get('/posts/{id}/show', [PostController::class, 'show'])->whereNumber('id');
How can I validate {id} to be greater than zero in the following route?
Route::get('/posts/{id}/show', [PostController::class, 'show'])->whereNumber('id');
Copyright © 2021 Jogjafile Inc.
Following the Laravel 9.x documentation, you should be able to do this:
You can see that regex works for
number >= 1
: https://regex101.com/r/MFxO2h/2Checking the source code, you can see that
whereNumber
isnumber >= 0
, that is why0
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 aPost
's ID, so your Route would be like this:Then, your controller:
If no
{post}
(id) matches a Post's ID, then404
, else the controller correctly executes the methodsshow
.