Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Route Parameter Validation with regex

Routing

Route Parameter Validation With Custom Regex

username must only contain lowercase letters

Route::get('/user/{username}', function(string $username) {
    // ...
})->where('username', '[a-z]+');

lang must always be 2 letters and id must contain at least 4 digits

Route::get("{lang}/product/{id}", function(string $lang, string $id) {
    // ...
})->where(["lang" => '[a-z]{2}', 'id' => '\d{4,}']);

Encoded Forward Slashes

By default Laravel allows every character to be presented in route parameter except /. If you want / to be matched in your route parameter as well you need to define the following ->where() on your route parameter.

Route::get('/search/{search}', function (string $search) {
    return $search;
})->where('search', '.*');

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!