Filtering Route with Regular Expressions in Laravel

Hello artisans, Today I will give you a short tips about the Laravel routes. Lets see the tips below.

Note: Tested on Laravel 8.65.

Table of Contents

  1. Route Filtering with regex
  2. Define Regex in a RouteServiceProvider

Route Filtering with regex

Suppose, you’ve a route named Route::get(‘product/{id}’, [\App\Http\Controllers\ProductController::class,’view’]) and you want id to strictly to be a number. To achieve that you’ve to use Regex with an where() condition like below

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

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

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

Define Regex in a RouteServiceProvider

We will use the previous route Route::get(‘product/{id}’, [\App\Http\Controllers\ProductController::class,’view’]), where you want to always use id as a number, then you can also specify it in the RouteServiceProvider. Just pase the below code in boot() method of your RouteServiceProvider.

Route::pattern('project_id', '[0-9]+');

That’s all for today. Thanks for reading ?