Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Restricting Laravel Routes with Regex Constraints

In a Laravel web application, a route connects an HTTP request, such as GET /users/42, to the code that handles it. A route parameter is a variable part of the URL, written in braces: {id} in /users/{id}. A regular expression, or regex, is a pattern that describes which text a parameter can contain.

Add a where constraint to a route so Laravel checks the parameter value as it looks for a matching route. For example, [0-9]+ matches one or more digits. With this pattern, /users/42 matches the route, but /users/alex does not.

Add where to the route definition

Place where after the route’s URI and handler. Pass the parameter name first and its regex pattern second:

Route::get('/users/{id}', [UserController::class, 'show'])
    ->where('id', '[0-9]+');

Laravel checks the constraint when it matches an incoming request to a route. If the id segment contains letters, this route does not match, so its controller does not handle that request. Laravel documents a 404 response when a request fails to match a route’s constraints. Another route or a fallback route can affect what handles the request instead. The Laravel routing documentation describes both parameter constraints and their effect on matching.

For a route with multiple parameters, pass an associative array that pairs each parameter name with its pattern:

Route::get('/users/{id}/{name}', [UserController::class, 'show'])
    ->where([
        'id' => '[0-9]+',
        'name' => '[a-z]+',
    ]);

Here, id must contain digits, and name must contain lowercase letters. Each pattern checks only the parameter named beside it. The patterns do not describe the entire URL.

Choose a pattern or a helper

Use a regex when the allowed values need a specific pattern. Laravel also provides helper methods for common parameter formats, including whereNumber, whereAlpha, whereAlphaNumeric, whereUuid, and whereUlid. For example, a numeric user ID and an alphabetic name can use:

Route::get('/users/{id}/{name}', [UserController::class, 'show'])
    ->whereNumber('id')
    ->whereAlpha('name');

Laravel’s routing documentation lists these helpers and shows whereIn for restricting a parameter to specified values. Use a helper when its category matches the URL format; use where when you need to express a more specific pattern.

To apply the same rule to every route parameter named id, define a global pattern with Route::pattern('id', '[0-9]+'). The provider location depends on the Laravel version: the 13.x documentation places it in AppServiceProvider::boot, while the 10.x documentation shows RouteServiceProvider::boot. Check the routing documentation for the version installed in your project before adding a global pattern.

Account for slashes and other checks

Laravel route parameters do not accept / by default. To let a parameter include slashes, explicitly allow them in its where pattern, such as with .*. Laravel supports encoded forward slashes only in the final route segment, so use this behavior only when the route is designed to accept a path-like value.

A route constraint controls which URL values match a route. It does not check whether a matched value exists in the database or whether a user is allowed to access it. Keep those checks in the code that handles the request. When a constraint rejects a URL, check whether another route or fallback handles the request before assuming the final response will be a 404.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *