In this example, I will show you how to use regular expressions in the Laravel route. Sometimes we need to specify the type of route parameter. In this case, we can use regular expressions.
We may constrain the format of our route parameters using the where
method on a route instance. This where
method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Now if we visit URLs like http://127.0.0.1:8000/user/john then it will work fine. But if we visit http://127.0.0.1:8000/user/1, then it will redirect us to a 404
page.
There are some examples of regular expressions in the Laravel route given below:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
We can also validate multiple route parameters with regular expressions like:
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->whereNumber('id')->whereAlpha('name');
Route::get('/user/{name}', function ($name) {
//
})->whereAlphaNumeric('name');
Route::get('/user/{id}', function ($id) {
//
})->whereUuid('id');
Route::get('/category/{category}', function ($category) {
//
})->whereIn('category', ['movie', 'song', 'painting']);
Read also: Laravel 9 Route Optional Parameter Example
Hope it can help you.