How to transfer Laravel parameters in Route

Learn how to pass parameters in Laravel routes with an example.

Transferring Laravel Parameters in Routes

Routes in Laravel provide a way to route requests to the appropriate controller or method. They can also be used to pass parameters from the URL to the controller or method. Here is an example of how to do this.

Route::get('user/{id}', function($id) {
     return 'User '.$id;
});

This route will match requests to /user/1, /user/2, and so on. The parameter {id} will be passed to the closure or controller method as the first argument. In this case, the value of $id will be set to the value of the parameter.

You can also specify constraints on parameters, such as only allowing integer values. This can be done by passing an array of constraints as the second argument to the Route::get() method:

Route::get('user/{id}', function($id) {
     return 'User '.$id;
})->where('id', '[0-9]+');

This route will only match requests to /user/1, /user/2, and so on. Any requests to /user/foo or /user/bar will not match. The parameters must match the regular expression specified in the where() method.

You can also specify more than one constraint by passing an array of constraints as the second argument to the Route::get() method:

Route::get('user/{id}/{name}', function($id, $name) {
     return 'User '.$id.' is named '.$name;
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

This route will only match requests to /user/1/john, /user/2/jane, and so on. The parameters must match the regular expression specified in the where() method for each parameter.

These are just a few examples of how to transfer parameters in Laravel routes. There are many more possibilities, such as using optional parameters, named parameters, and more. For more information, see the Laravel Routing Documentation.

Answers (0)