Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to validate Route Parameters in Laravel?
In Laravel, route parameter validation ensures that URLs match specific patterns before executing route handlers. Laravel provides several builtin methods to validate route parameters, making your application more secure and predictable.
Route Parameters Syntax
Route parameters are defined within curly braces and can contain alphanumeric characters and underscores ?
<?php
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
?>
Multiple Route Parameters
You can define multiple parameters in a single route ?
<?php
Route::get('/students/{post}/feedbacks/{feedback}', function ($postId, $feedbackId) {
return "Post: $postId, Feedback: $feedbackId";
});
?>
Optional Parameters
Optional parameters are denoted with ? and require default values ?
<?php
Route::get('/students/{name?}', function ($name = 'Guest') {
return "Hello " . $name;
});
?>
Using where() Method
The where() method applies custom regex validation to route parameters ?
<?php
Route::get('/student/{name}', function ($name) {
return "Student: " . $name;
})->where('name', '[A-Za-z]+');
?>
For multiple parameters, use an array ?
<?php
Route::get('/student/{id}/{name}', function ($id, $name) {
return "ID: $id, Name: $name";
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
?>
Using whereNumber() Method
The whereNumber() method validates that a parameter contains only numeric values ?
<?php
Route::get('/student/{id}/{name}', function ($id, $name) {
return "Student ID: $id, Name: $name";
})->whereNumber('id')->where('name', '[a-z]+');
?>
Using whereAlpha() Method
The whereAlpha() method ensures parameters contain only alphabetic characters ?
<?php
Route::get('/student/{id}/{name}', function ($id, $name) {
return "Student ID: $id, Name: $name";
})->whereNumber('id')->whereAlpha('name');
?>
Using whereAlphaNumeric() Method
The whereAlphaNumeric() method accepts both letters and numbers ?
<?php
Route::get('/student/{id}/{username}', function ($id, $username) {
return "ID: $id, Username: $username";
})->whereNumber('id')->whereAlphaNumeric('username');
?>
Validation Methods Comparison
| Method | Validates | Example Pattern |
|---|---|---|
where() |
Custom regex | [A-Za-z]+ |
whereNumber() |
Numeric only | 123, 456 |
whereAlpha() |
Letters only | john, Mary |
whereAlphaNumeric() |
Letters and numbers | user123, abc456 |
Conclusion
Laravel's route parameter validation methods provide a clean way to ensure URL parameters meet specific criteria. Use whereNumber(), whereAlpha(), and whereAlphaNumeric() for common patterns, or where() for custom regex validation.
