Routing with Parameters

Routing Parameters  

Often in the application, we intend to capture the parameters passed with the URL. To do this, we need to modify the code in routes.php file accordingly. There are two ways by which we can capture the parameters passed with the URL. 

  • Required Parameters
  • Optional Parameters 

Required Parameters 

These parameters must be present in the URL. For example, you may intend to capture the ID from the URL to do something with that ID. Here is the sample coding for routes.php file for that purpose. Route::get('ID/{id}',function($id){

 echo 'ID: '.$id;

 }); 

Whatever argument that we pass after the root URL (http://localhost:8000/ID/5), it will be stored in $id and we can use that parameter for further processing but here we are simply displaying it. We can pass it onto view or controller for further processing.

Optional Parameters 

There are some parameters which may or may not be present in the URL and in such cases we can use the optional parameters. The presence of these parameters is not necessary in the URL. These parameters are indicated by “?” sign after the name of the parameters. Here is the sample coding for routes.php file for that purpose.

//Route Parameters
// Route method – Root URL with ID will match this method

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

// Route::get('/about/{name?}', function () {
//     return 'Testing';
// });

Route::get('/user/{name?}',function($name = 'Aqib'){

    echo "Name: ".$name;
   
    });

Note: Regular expression can also be used to match the parameters

Comments