Complete CodeIgniter 4 URI Routing Tutorial in Depth

Reading Time: 7 minutes
7,775 Views

Inside this article we will see the concept i.e Complete CodeIgniter 4 URI Routing Tutorial in Depth. Article contains the classified information about URI Routing, Services, Redirection in CodeIgniter 4.

In CodeIgniter 4, we will see that routes configuration is totally different from it’s previous version. Routes configuration are the application level configuration which controls the application redirection.

Inside this tutorial 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 –

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.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# 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 about Complete CodeIgniter 4 URI Routing Tutorial in Depth in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.