Route patterns

Route patterns

Dec 19, 2016,

If you're using repeating ->where() in your routes like these:

Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z0-9]{2,32}');

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

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[A-Za-z0-9]{2,32}']);

You might find it useful use Global Constraints.

All you need to do is to update your RouteServiceProvider::boot():


    public function boot()
    {
        Route::pattern('id', '\d+');
        Route::pattern('name', '[A-Za-z0-9]{2,32}');
        Route::pattern('title', '[a-z0-9-]+');

        parent::boot();
    }

After that your routes would be much prettier: And easier to support such patterns.

// get article by a slug
Route::get('article/{title}, function ($title') {
    // Only executed if {title} is a slug (alphanum + '-')
});

// get user by id and name
Route::get('user/{id}/{name}', function ($id, $name) {
    // Only executed if {id} is numeric and {name} is alphanum (length between 2 and 32)
});