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

Like our articles?
Check out our Laravel online courses!

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here