How to pass parameter in Laravel route?

by elise_daugherty , in category: PHP Frameworks , 2 years ago

How to pass parameter in Laravel route?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by aniya.jaskolski , 2 years 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

by ryan.murray , a year ago

@elise_daugherty 

To pass parameters in Laravel routes, you can use the {} brackets to define the parameter within the route URL. Here is an example:

  1. Define the route with a parameter:
1
2
3
4
Route::get('/user/{id}', function ($id) {
    // Access the $id parameter here
    // Do something with the $id parameter
});


  1. Access the parameter in your controller or closure callback:
1
2
3
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});


  1. Access the parameter in your view:
1
2
3
Route::get('/user/{id}', function ($id) {
    return view('user', ['id' => $id]);
});


In your user.blade.php view, you can now access the $id parameter like this: {{ $id }}.


You can also define multiple parameters in a single route:

1
2
3
Route::get('/user/{id}/post/{postId}', function ($id, $postId) {
    // Access both $id and $postId parameters here
});


Note: You can use any name within the {} brackets as the parameter placeholder, and it will be passed to the closure or controller method in the same order.