Laravel Route Filtering with Regular Expressions

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();
}

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 57 courses (1055 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials