How would you make sure a route parameter id
is always a numeric value. Most of the time an id
parameter will be an integer value. So today’s tutorial we will show how to globally constrain a parameter to a regular expression.
You should define these patterns in the boot method of your App\Providers\RouteServiceProvider
class.
In the boot method you will write like this
/** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { Route::pattern('id', '[0-9]+'); }
So we are ready with the pattern in the boot method, now declare the route in web.php or api.php or whatever route file is used by your application.
Route::get('/user/{id}', function ($id) { // Only works if the id is numeric value });
That’s it! For testing, you can try to input some non-numeric values and you will see how it’s working. Basically, this avoids the hassle of writing a validation for each and every id
parameter individually.
Related Articles
- Laravel 8 – Ajax File Upload with Progress Bar
- Laravel 8 Create Custom Helper Functions (Global function)
- Force HTTPS with a Middleware in Laravel
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.