In Laravel, you can use regular expression constraints to validate route parameters directly in the route definition. This ensures your application only processes requests with parameters that match the expected format.
// Constrain {year} to a 4-digit number
Route::get('/archive/{year}', function ($year) {
// ...
})->where(['year' => '[0-9]{4}']);
// Constrain {slug} to alphanumeric characters with dashes or underscores
Route::get('/post/{slug}', function ($slug) {
// ...
})->where('slug', '[A-Za-z0-9-_]+');
// Constrain {type} to specific values
Route::get('/media/{type}', function ($type) {
// ...
})->whereIn('type', ['video', 'audio', 'image']);
You can also define global constraints using Route::pattern()
method.