Filter URL Routes With Regular Expressions

Routes in Laravel are extremely powerful and can make your job much easier if you know how to use all of their features. One of these features is the ability to filter URLs by using regular expressions.

Using regular expression contraints on your routes is extremely simple and it looks similar to Eloquent. You will only have to use a where method.

How to filter URL routes by using regular expression constraints

Like I've said before, we're going to use the where method, which takes two parameters. First is the segment name and the second is the regular expression.

So let's say we want to get the route if it contains only letters:

Route::get('user/{name}', function ($name) {
})->where('name', '[A-Za-z]+');

By using constraints we can keep using the user segment, while the second one will now represent the id, instead of the name. For this we will only get the segments that contain just numbers. Without contraints this would have been impossible.

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

Now you can expand this further and make use of the filters or contraints to use btter routes.