Skip to main content
Tutorial Free

Laravel Route Filtering with Regular Expressions

February 14, 2019
2 min read

Quick tip of the day. With routing you can specify Route::get('projects/{project_id}', 'ProjectController@show'); but what if you want project_id to be strictly a number?

To achieve that, you can put where() condition on any Route statement, and use regular expressions for specifying data pattern.

Here are examples from official Laravel documentation:

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

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

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

Another example would be restricting some parameter to be one of a few strict values, then avoid checking it in Controller:

Route::get('/user/{user_id}/{approve_action}','UserController@approve')
    ->where('approve_action', 'approve|decline');

If you put these conditions, then route will match only those within regular expressions, so if you enter URL /user/123 it will show 404 page.

Not only that, you can specify that some variable name would always follow a certain pattern. Like, for example, you want project_id in all routes to be integer. Then you do this in app/Providers/RouteServiceProvider.php:

public function boot()
{
    Route::pattern('project_id', '[0-9]+');
    parent::boot();
}

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.