How To Filter Laravel Routes With Regular Expressions

One thing Laravel is really great for is the ability to run over regex rules on parameters before returning a view. This, of course, has many benefits, one of which is to stop unethical users from trying to submit, potentially dangerous data to the backend of your system.

In Laravel, you can apply regular expression queries to make sure the parameters submitted via HTTP requests have the right data within them. Chaining function calls to our standard routes can enable strict regex filtering and prevent unwanted URL requests. Learn how to apply regex patterns in the following sections.

So how do we do it?

The magical function that allows this excellence is ->where()

Let’s assume we have a Store website, it sells a variety of products that have their own relevant categories. The store allows a single string parameter to identify the category of the store. For example,

We know that this parameter needs to be a string and therefore, no numeric or special characters are allowed.

Let’s define our route to handle these rules

Route::get('/store/{category?}', 'StoreController@index')
     ->where('category', '[A-Za-z]+');
  • This specific route will now only render the view if the URL is something like –
  • If we tried or, Laravel will render the 404 page.
  • This is because the regex applied to the routes parameter will only match lowercase a through to z.

Now let’s enhance this route by allowing a product ID to be part of the URL too. So for example,

Route::get('/store/{category?}/{id?}', 'StoreController@index')
    ->where('category', '[a-z]+')
    ->where('id', '[0-9]+');
  • This enhanced route will now only render the view if the parameter for the category is alpha characters and the product ID is numeric like the example earlier –
  • If we tried or, Laravel will render the 404 page.
  • This is because, in addition to the category parameter rules, a regex is applied to the ID, making sure it is only numeric characters.


With these basic examples, you can see how you could apply a vast array of rules to parameters that are being submitted via URL’s. This removes the need to handle these pieces of data within your controller, keeping your controllers slim and clean. The examples shown in the above routes are only simple regex patterns, these could be expanded to your leisure and accept/deny all sorts of types of URL requests.



Leave a Reply