Here Is How To Get Laravel Route Parameters The Right Way

Here Is How To Get Laravel Route Parameters The Right Way

If the route you are defining has parameters (segments) in the URL structure that are variable – it’s simple to define them in your route and pass them to your closure.

Route::get('users/{id}/friends', function($id) {
// The rest of the code here

The Naming Relationship Between Route Parameters and Closure/Controller Method Parameters

It’s most common to use the same names for your route parameters {$id} and the method parameters inject into your route definition function($id). But is this necessary ?

Unless you are using route/model binding, no. The only thing that defines which route parameters matches with which method parameter is their order (left to right), as you can see here:

Route::get('users/{user_id}/comments/{comment_id}', function(
    ) {

With that said, just because you can make them different doesn’t mean you should. I recommend keeping them the same for the sake of future developers, who could get tripped up by inconsistent naming.

You can also make your route parameters optional by including a question mark (?) after the parameter name. In this case you should also provide a default value for the route’s corresponding variable.

Route::('users/{id?}', function ($id => 'fallback_id') {

Regular expressions

You can also use regular expressions if you are well-versed with it, to define that a route should only match if a parameter meets particular requirements such as:

Route::get('users/{id}', function($id) {
// Only numbers for ID accepted
})->where('id', '[0-9]+');