DEV Community

Mahmoud Abdelfadiel
Mahmoud Abdelfadiel

Posted on

Laravel : How to Create a regular expression constraints on the parameters in the routes file


Route::get('test/{id}', function(){
    return 'test page ';
});

// id=xxxxxxxxxx

// http://127.0.0.1:8000/test/xxxxxxxxxx 
// output => test page 

Enter fullscreen mode Exit fullscreen mode

Image description

Add condition id => any number integer unsigned = [0-9]+

Route::get('test/{id}', function(){
    return 'test page ';
})->where(['id' => '[0-9]+']);

// id=xxxxxxxxxx

// http://127.0.0.1:8000/test/xxxxxxxxxx 
// output 404 NOT FOUND

// id=10 

// http://127.0.0.1:8000/test/10 
// output => test page 

Enter fullscreen mode Exit fullscreen mode

You can make the condition on the whole project

open app/Providers/RouteServiceProvider.php;

 public function boot()
 {
        Route::pattern('id', '[0-9]+');
        parent::boot();
 }
Enter fullscreen mode Exit fullscreen mode

Reference

https://laravel.com/docs/9.x/routing#parameters-regular-expression-constraints

Top comments (0)