CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
Routing in CodeIgniter determines how URL requests are handled and which controller/method should process them. Instead of mapping URLs directly to file paths, CodeIgniter uses routes to decide which code should run.
When a user visits a URL, CodeIgniter’s routing system checks its app/Config/Routes.php
file to determine which controller and method should handle the request.
https://example.com/blog/view/1
Here:
Blog.php
)view()
)By default, CodeIgniter uses this route:
$routes->get('/', 'Home::index');
/
means the home page.Home
is the controller.index
is the method.If you want a different controller for the homepage:
$routes->get('/', 'Welcome::index');
Now visiting /
will run Welcome
controller’s index()
method.
You can pass dynamic values to methods using placeholders.
$routes->get('product/(:num)', 'Product::view/$1');
(:num)
→ matches only numbers.$1
→ passes the matched value to the method.CodeIgniter has several placeholders:
(:num)
→ Numbers only(:alpha)
→ Alphabets only(:alphanum)
→ Alphabets + Numbers(:any)
→ Anything except a forward slash(:segment)
→ Any valid URI segmentYou can restrict routes to specific HTTP methods:
$routes->post('submit-form', 'FormController::submit'); $routes->put('update/(:num)', 'Product::update/$1'); $routes->delete('delete/(:num)', 'Product::delete/$1');
Groups help organize related routes with a common prefix.
$routes->group('admin', function($routes) { $routes->get('dashboard', 'Admin\Dashboard::index'); $routes->get('users', 'Admin\Users::index'); });
Now:
/admin/dashboard
/admin/users
You can name a route for easier URL generation:
$routes->get('login', 'Auth::login', ['as' => 'login']);
Then use:
url_to('login');