DEV Community

Gregori Piñeres
Gregori Piñeres

Posted on • Updated on

Define regex constraints to your Laravel routes easy.

In the next version 8.12.x of laravel a method will be added that will save you several lines of code if you are defining restrictions on your routes.

Previously, in most projects that implemented this feature, you would see code like the following.

<?php

use Illuminate\Support\Facades\Route;

Route::get('articles/{article}', 'ArticleController@show')
  ->where(['article' => '[0-9]+']);
Enter fullscreen mode Exit fullscreen mode

With this syntax we would match with a route similar to the following.

URL HTTP Status Code
https://example.com/articles/123456 200
https://example.com/articles/abcdfg 404

This is fine, but some users may not understand this syntax at first glance. Therefore, now we will have a series of explicit methods that will allow the developer to save code and obtain the same result without writing "complex" expressions.

New route regex registration methods

Method Regex
whereNumber [0-9]+
whereAlpha [a-zA-Z]+
whereUuid [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}

Finally you can use these methods in the definition of the routes as follows.

<?php

use Illuminate\Support\Facades\Route;

Route::get('articles/{article}', 'ArticleController@show')
  ->whereNumber('article');

Route::get('user/{user}', 'UserController@show')
  ->whereUuid('user');

Route::get('book/{author}/{title}', 'BookController@show')
  ->whereString(['author', 'title']);
Enter fullscreen mode Exit fullscreen mode

As you know this feature will be available from version 8.12.0 of the framework, I hope it will be useful for you.

We read soon.

Top comments (0)