What are route patterns in Laravel?

Laravel: What are route patterns in Laravel?

In your routes file you can add code like this:

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

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

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

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:

  1. Route::pattern('slug', '[a-z0-9-]+');
  2. Route::pattern('hash', '[a-z0-9]+');
  3.  
  4. Route::get('forum-thread/{slug}', '[email protected]'); // {slug} has to be alpha numeric (lowercase), but can include a dash
  5. Route::get('forum-post/{hash}', '[email protected]'); // {hash} has to be alpha numeric, lowercase

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What are route patterns in Laravel?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to add the CSRF (Cross-site request forgery) token in Laravel?

How to use Anonymous classes in PHP 7?

What are Template literals (Template strings) in JS?

How to undelete a soft deleted Eloquent row?

What are generators in PHP, and how do they compare to arrays?

How to query mysql using PDO in PHP?

How to order a Laravel hasMany relationship?

How to manually write your own pagination in PHP

A list of operators on Eloquent's where() method

How to set the Expires header in .htaccess