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

Loading video...

Route Parameter Validation

Routing

Route Parameter Validation

You can define what should be the format of each route parameter.

Route::get("/product/{id}", function(string $id) {
		// ...
})->whereNumber("id"); // Only digits

Matches the following routes

  • /product/1
  • /product/01234
  • /product/56789

Does not match!!

  • /product/test
  • /product/123test
  • /product/test123

username must only contain uppercase and lowercase letters

Route::get('/user/{username}', function(string $username) {
    // ...
})->whereAlpha('username');

Matches the following routes

  • /user/zura
  • /user/thecodeholic
  • /user/ZURA

Does not match!!

  • /user/zura123
  • /user/123ZURA

username must only contain uppercase, lowercase letters and digits

Route::get('/user/{username}', function(string $username) {
    // ...
})->whereAlphaNumeric('username');

Matches the following routes

  • /user/zura123
  • /user/123thecodeholic
  • /user/ZURA123

Does not match!!

  • /user/zura.123
  • /user/123-ZURA
  • /user/123_ZURA

You can also define constrains for several route parameters

Route::get("{lang}/product/{id}", function(string $lang, string $id) {
		// ...
})
    ->whereAlpha("lang") // Only uppercase and lowercase letters
    ->whereNumber("id") // Only digits
;

Matches the following routes

  • /en/product/123
  • /ka/product/456
  • /test/product/01234

Does not match!!

  • /en/product/123abc
  • /ka/product/abc456
  • /en123/product/01234

lang route parameter must contain one of the provided values. Anything else will not match the route

Route::get("{lang}/products", function(string $lang) {
    // ...
})->whereIn("lang", ["en", "ka", "in"]);

Matches the following routes

  • /en/products
  • /ka/products
  • /in/products

Does not match!!

  • /de/products
  • /es/products
  • /test/products

Discussion

Sign in to join the discussion.

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