How to check route parameters with regular expressions

I’m pretty sure that majority of you haven’t read ALL official Laravel documentation – you work only with functions you actually need and know, right? So I like to dig up some less known or “hidden” features which are new to many people. So today one of those “Did you know?” cases.

Routing mechanism allows us to specify parameters in URL, like this:

Route::get('user/{name}', function ($name) { // ...

Or with Controller:

Route::get('user/{id}', 'UserController@showProfile');

But how do we make sure that the parameter is, for example, a number? In the second example – we need the user ID to be integer, right?

Of course, we will make validation in Controller or in Middleware. But we can easily make it even before then – in the same routes.php file, like this:

Route::get('user/{id}', 'UserController@showProfile')
->where('id', '[0-9]+');

Basically, Route commands except additional function where(field, expression) where you can check whatever you want with regular expressions.

Same can work for more than one parameter – just specify an array in where() function:

Route::get('user/{id}/{name}', function ($id, $name) {
->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

If the validation fails, route would not be found and a visitor would get 404 error, or whatever you specify on handling “Route not found” case.

The same short explanation can be found in the official documentation.

Like our articles?
Check out our Laravel online courses!



Please enter your comment!
Please enter your name here