How to pass parameter in Laravel route?

by elise_daugherty , in category: PHP Frameworks , 9 months ago

How to pass parameter in Laravel route?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 3 months ago

@elise_daugherty 

In Laravel, you can pass parameters to a route by including them in the URL path. To specify a parameter in the URL path, you should use curly braces {} around the parameter name. For example, if you want to pass a parameter named "id" to a route, you would include it in the URL path like this:

1
2
3
Route::get('user/{id}', function ($id) {
    //
});


In this example, when the route is matched, the value of the id parameter in the URL path will be passed to the closure function as an argument.


You can also specify multiple parameters in the URL path, like this:

1
2
3
Route::get('user/{id}/{name}', function ($id, $name) {
    //
});


In this case, when the route is matched, both the id and name parameters in the URL path will be passed to the closure function as arguments.


You can also use same notation for controller method

1
Route::get('user/{id}/{name}', 'UserController@show');


The corresponding show method in the UserController class should expect two parameters for the given route.


You can also specify a regular expression pattern that the parameter should match, by providing an array with the regular expression pattern as the first element, and the parameter name as the second element:

1
2
3
Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');


this will only match the routes where id is numeric and don't have any string characters