This is very common to every web application i.e Passing parameters to URLs. Also called as parameterized routing of application.
We will see about URL Placeholders & With Parameters in this section.
URL Placeholders
In CodeIgniter 4 application, there are several types of placeholder available to pass value to URL. Parameters as like of type Integer value, String value, Hashed value, Alpna numeric etc.
![](https://onlinewebtutorblog.com/wp-content/uploads/2020/10/Screenshot.png)
Let’s take an example to see How can we pass and access value to controller?
Open Routes.php file from /app/Config folder.
//... $routes->get("my-route/(:num)", "MyController::myRoute/$1"); $routes->get("sample-route/(:any)/(:num)", "MyController::sampleRoute/$1/$2");
Here, we have configured few routes.
- First route will take a numeric value into URL as (:num) placeholder. We can pass any value there is no restriction with this placeholder i.e (:num) means only integer value. But I suggest, while developing any kind of application all things should be meaningful. That’s why use (:num) only when pass numeric value into URLs.
- $1 in first route – Passing url value to myRoute() method.
- Second route will take 2 values – one is any type means integer, string etc and other is for numeric value.
- $1 is for (:any) value and $2 is for numeric value. These two values $1 & $2 we are passing inside sampleRoute() method.
Example URLs
- /my-route/12
- /my-route/45 … etc
- /sample-route/hi/40
- /sample-route/256/120
Access URL values to Controller
<?php namespace App\Controllers; use App\Controllers\BaseController; class MyController extends BaseController { public function myRoute($id) { // .. code here } public function sampleRoute($key, $id) { // .. code here } }
- myRoute($id) – Get (:num) value to method. This $id variable contains the URL value.
- sampleRoute($key, $id) – Get (:any) & (:num) value. These two variables contains the URL value.