CodeIgniter Routing

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. 


1. What is Routing in CodeIgniter?

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 → Controller name (Blog.php)
  • view → Method name (view())
  • 1 → Parameter passed to the method


2. Default Routing

By default, CodeIgniter uses this route:


$routes->get('/', 'Home::index');


  • / means the home page.
  • Home is the controller.
  • index is the method.

3. Setting a Default Controller


If you want a different controller for the homepage:


$routes->get('/', 'Welcome::index');


Now visiting / will run Welcome controller’s index() method.




4. Passing Parameters in Routes


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.

5. Route Placeholders

CodeIgniter has several placeholders:

  • (:num) → Numbers only
  • (:alpha) → Alphabets only
  • (:alphanum) → Alphabets + Numbers
  • (:any) → Anything except a forward slash
  • (:segment) → Any valid URI segment


6. HTTP Method-Specific Routes

You 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');


7. Route Groups

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


Named Routes

You can name a route for easier URL generation:

$routes->get('login', 'Auth::login', ['as' => 'login']);

Then use:

url_to('login');



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.