How to Use Route Parameters in Laravel: Simple Guide
In Laravel, you use
{parameter} syntax in your route URI to define route parameters. These parameters are passed to your controller methods or route closures as arguments automatically.Syntax
Route parameters are defined by wrapping a segment of the URI in curly braces {}. Laravel captures this segment and passes it to your route's callback or controller method.
- {parameter}: Required parameter that must be present in the URL.
- {parameter?}: Optional parameter that may or may not be present.
- Where constraints: You can restrict parameter values using
wheremethod.
php
use Illuminate\Support\Facades\Route; // Required parameter Route::get('/user/{id}', function ($id) { return "User ID: $id"; }); // Optional parameter Route::get('/post/{slug?}', function ($slug = null) { return $slug ? "Post: $slug" : 'No post slug provided'; }); // Parameter with constraint Route::get('/product/{id}', function ($id) { return "Product ID: $id"; })->where('id', '[0-9]+');
Example
This example shows a route with a required parameter {name}. When you visit /hello/John, it returns a greeting with the name.
php
use Illuminate\Support\Facades\Route; Route::get('/hello/{name}', function ($name) { return "Hello, $name!"; });
Output
Hello, John!
Common Pitfalls
Common mistakes include:
- Not matching the parameter name in the route and the callback function.
- Forgetting to provide a default value for optional parameters.
- Not using constraints when expecting specific formats (like numbers).
- Defining routes with parameters in the wrong order, causing conflicts.
php
// Wrong: parameter name mismatch Route::get('/user/{id}', function ($userId) { return $userId; // This will cause an error because parameter name is 'id' }); // Right: matching parameter name Route::get('/user/{id}', function ($id) { return $id; }); // Wrong: optional parameter without default Route::get('/post/{slug?}', function ($slug) { return $slug; }); // This will cause an error if slug is missing // Right: optional parameter with default Route::get('/post/{slug?}', function ($slug = null) { return $slug ?? 'No slug'; });
Quick Reference
| Feature | Syntax | Description |
|---|---|---|
| Required parameter | /user/{id} | Captures 'id' from URL and passes to callback |
| Optional parameter | /post/{slug?} | Parameter 'slug' may be missing; provide default value |
| Parameter constraint | ->where('id', '[0-9]+') | Limits 'id' to numeric values only |
| Multiple parameters | /order/{orderId}/item/{itemId} | Capture multiple values from URL segments |
Key Takeaways
Define route parameters using curly braces in the route URI.
Parameter names in the route and callback must match exactly.
Use optional parameters with default values to avoid errors.
Apply constraints to parameters to enforce valid formats.
Order routes carefully to prevent conflicts with similar patterns.