What are route patterns in Laravel?

October 26, 2018

In your routes file you can add code like this:

    Route::pattern('id', '[0-9]+'); 

Then you can use that pattern later on in your routes file like this:

Route::get('user/{id}', function ($id) {
    // Only executed if {id} is numeric...

I've not seen this used too often, however this is a useful feature and keeps things quite clean.

Some other examples of defining some route patterns:

Route::pattern('slug', '[a-z0-9-]+');
Route::pattern('hash', '[a-z0-9]+');
Route::get('forum-thread/{slug}', 'ForumController@viewThread'); // {slug} has to be alpha numeric (lowercase), but can include a dash
Route::get('forum-post/{hash}', 'ForumController@hash'); // {hash} has to be alpha numeric, lowercase