Laravel Route Parameters Tutorial
When defining routes, sometimes you need to capture parts of the URL (like user IDs or names). Laravel makes this simple with route parameters.
Required Parameters
You can capture values from the URL by wrapping them in {} braces.
Route::get('/user/{id}', function (string $id) {
return "User " . $id;
});
Visiting /user/5 will return:
User 5
You can also define multiple parameters:
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
return "Post: $postId, Comment: $commentId";
});
Parameters with Dependency Injection
If you need both services (like Request) and route parameters, always list dependencies first:
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, string $id) {
return "User " . $id . " with IP " . $request->ip();
});
Optional Parameters
Sometimes, the parameter is not always required. Use ? and provide a default value:
Route::get('/user/{name?}', function (?string $name = 'John') {
return $name;
});
/user → returns John/user/Ali → returns Ali
Regular Expression Constraints
You can restrict parameter values with regex using where:
Route::get('/user/{id}', function (string $id) {
return "User ID: $id";
})->where('id', '[0-9]+'); // Only numbers allowed
/user/10 works, but /user/abc gives 404.
Multiple constraints:
Route::get('/user/{id}/{name}', function (string $id, string $name) {
return "ID: $id, Name: $name";
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
Helper Methods for Constraints
Laravel provides shortcut methods for common patterns:
Route::get('/user/{id}', fn($id) => $id)->whereNumber('id');
Route::get('/user/{name}', fn($name) => $name)->whereAlpha('name');
Route::get('/user/{name}', fn($name) => $name)->whereAlphaNumeric('name');
Route::get('/user/{id}', fn($id) => $id)->whereUuid('id');
Route::get('/user/{id}', fn($id) => $id)->whereUlid('id');
Restrict values to specific options:
Route::get('/category/{category}', fn($c) => $c)
->whereIn('category', ['movie', 'song', 'painting']);
Global Constraints
If you always want a parameter (like id) to follow certain rules, define it globally in AppServiceProvider:
use Illuminate\Support\Facades\Route;
public function boot(): void
{
Route::pattern('id', '[0-9]+');
}
Now, all {id} parameters in routes will only accept numbers.
Encoded Forward Slashes
By default, / is not allowed in parameters. If you want to allow it (e.g., for search strings), use .*:
Route::get('/search/{search}', function (string $search) {
return $search;
})->where('search', '.*');
/search/hello/world works
Note: Only works on the last route segment.
Important
{id}→ Required parameter{name?}→ Optional parameterwhere()→ Add regex constraintswhereNumber,whereAlpha,whereUuid, etc. → Built-in helpersRoute::pattern()→ Global constraints.*→ Allow/in the last parameter
