CI 4 What are Named Routes?

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.

When we create any route, we also have a option to add name to any route. We can call that name to any linking at view file while creating routes.

$routes->get('/about-us', 'Home::aboutUs', ['as' => 'about']);

Here, /about-us is URL route, Home is controller, aboutUs is a method from Home controller and about is the name of the route.

To define name to any route, use ‘as’ keyword.

//...

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

// OR

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

//...

How To Use Named Routes?

Usage of Named routes is pretty very simple. We can use it inside redirection or we can use it in view for linkings.

Usage in Redirection

In CodeIgniter 4, for redirection we use redirect() function.

//...

$routes->get('/sample-url', function(){
     // product is the name of "our-products" route. Look above.
	 return redirect('products'); 
});

//...

When we type /sample-url into URL, it will redirect to /our-products route. Here, we have used the concept of named route.

Usage in Route Linking

There are several ways to create anchor links in CodeIgniter 4. Here we will use route_to() function.

<a href="<?php echo route_to('products') ?>">Our Products</a>

<a href="<?php echo route_to('services') ?>">Our Services</a>

We can see we have used the names of routes instead the URL.

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.