Laravel 7.x Route Filtering with Regular Expressions

Hello Artisan

In this tutorial i will discuss about laravel route filter with regular expression. Do you know we can use where condition with routing. If you don't know how to filter routing with regular expression then you can follow you. 

Suppose think Route::get(‘projects/{project_id}’, ‘[email protected]’); but what if you want project_id to be strictly a number? To achieve the goal, you can put where() condition on any Route statement, and use regular expressions for specifying data pattern. See the example code of regular expression. 

Filter using letter

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

 

Filter with only numbers

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

 

Filter with few condition on a few parameter

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

 

Read also : Laravel Search Multiple Models using Spatie Searchable Package

 

Hope it can help you.