Complete CodeIgniter 4 Routing Tutorial in Details

Share this Article
Reading Time: 7 minutes
1,041 Views

In CodeIgniter 4, we will see that routes configuration is totally different from it’s previous version. Inside this article we will learn about CodeIgniter 4 Routing Tutorial in deep concept.

Routes configuration are the application level configuration which controls the application redirection. Inside this we will cover Basics of routes, Route Closure, Named Routes, HTTP methods, about URL segment placeholders.

Also you can find the complete basics of CodeIgniter 4 from here.

Learn More –

  • Route Group Tutorial in CodeIgniter 4, Click here.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


What are Routes?

In any application Routes are the responsible section for responding the URL requests. In CodeIgniter 4 routes can be configured in /app/Config/Routes.php file. When application requests any URLs, routes checked inside this file.

Here, we will see these followings.

  • Basics of routes
  • Route Closures
  • Route Placeholders
  • Named Routes
  • HTTP methods

To learn about Route Grouping in CodeIgniter 4, Click here.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


CodeIgniter 4 Basic Routes

In CodeIgniter 4 application, creating routes includes method type. We can use following methods like $routes->get(), $routes->post(), $routes->match(), $routes->add() etc.

$routes is an instance of RouteCollection class.

//...

// Using add() method
$routes->add("about-us", "Site::aboutUs");
$routes->add("products", "Site::ourProducts");
$routes->add("services/(:num)", "Site::services/$1");

// Using get() method
$routes->get("about-us", "Site::aboutUs");
$routes->get("products", "Site::ourProducts");
$routes->get("services/(:num)", "Site::services/$1");

//...

Inside these routes, we need to create and process request by using controller’s method.


CodeIgniter 4 Route Closures

When we define route closures, it means we are going to call request function in route file itself. Have a look,

//...

// route with static message
$routes->get("contact-us", function () {

    echo "<h1>Welcome to Online Web Tutor</h1>";
});

// route with view file
$routes->get("about-us", function () {

    return view("about-us"); // /app/Views/about-us.php
});

// route with parameter
$routes->get("services/(:num)", function ($id) {

    echo "ID: ".$id;
});

//...

CodeIgniter 4 Route Placeholders

While defining application routes, we can also create parameterized routes. You can see in above routes we have passed (:num), it means passing integer value to route. It’s a value placeholder.

So here, we have different different placeholders to pass values to routes.

//...

// To pass integer value to route
$routes->get("services/(:num)", "Site::services/$1");
// Example : services/1, services/203, services/522

// To pass any characters
$routes->get("services/(:any)", "Site::services/$1");
// Example : services/1, services/4.55, services/sample-service

// To pass alphabetics
$routes->get("services/(:alpha)", "Site::services/$1");
// Example : services/sample-service

// To pass alphabets and numbers in URL
$routes->get("services/(:alphanum)", "Site::services/$1");
// Example : services/service-cod-1002

//...

To pass multiple values in Routes, we can do as –

//...

// To pass number, alphabet
$routes->get("services/(:num)/(:alpha)", "Site::services/$1/$2");
// Example : services/101/sample-service

//...

CodeIgniter 4 Named Routes

When we create any route, we also have a option to add name to any route. Named route simply means a route which has a name, we can use it’s name to call it as simple as that to understand.

We can call that name to any linking at view file while creating routes.

//...

// Create routes
$routes->add('our-services', 'Site::services', ['as' => 'services']);

// OR

$routes->get('our-services', 'Site::services', ['as' => 'services']);

// Use it in a view
<a href="<?= route_to('services') ?>">Service</a>
  
//...  
  

route_to() is a helper function to call routes or for creating links in view files. Lean in more detail about Named route, Click here.


CodeIgniter 4 Route Redirection

If our site have some pages that have been moved or say may be temporary on hold, we can assign a new redirect routes that will send a 302 (Temporary) Redirect status for those and process the user to the correct page.

//...

$routes->addRedirect('about-us', 'contact-us');

//...

This will redirect users when they try to open about-us to the new location at contact-us


HTTP Request Methods

There are other methods also available other than get() and add() method. These methods process according to the request when we hit the URL. Here, we have the available route methods. Have a look,

//...

$routes->get('services', 'Site::services');
$routes->post('services', 'Site::services');

// OR When we have the same route with different different request types
$routes->match(["get", "post"], 'services', 'Site::services');

$routes->put('services/(:num)', 'Site::services/$1');
$routes->delete('services/(:num)', 'Site::services/$1');

//...

Spark Routes List

When we define routes in application means at /app/Config/Routes.php, then by the help of spark command we can list all available routes to CLI.

More about Spark CLI Tool, click here.

Here, we have some routes defined inn /app/Config/Routes.php file :

//...

$routes->match(["get", "post"], 'services', 'Site::services');
$routes->put('services/(:num)', 'Site::services/$1');
$routes->delete('services/(:num)', 'Site::services/$1');

//...

Back to terminal, type the command $ php spark routes

Successfully, we have completed step by step tutorial for CodeIgniter 4 Routing. For more details also you can see the document of official website of CodeIgniter 4.

We hope this article helped you to learn CodeIgniter 4 Routing Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here