CakePHP 4 How To Use Named Route Tutorial

Reading Time: 3 minutes
1,482 Views

Inside this article we will understand CakePHP 4 how use named route. Named route means a route which has a name. We can use it’s name to call that specific route. This article contains classified information about usage of named route in cakephp application.

Tutorial contains very easy understanding over Named routes. We use generally _name for named routes which is also a reserved keyword in cakephp for routes. When we define named routes, then instead of calling the route full path we use it’s _name keyword value.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Named Routes

Open routes.php file from /config folder.

//...

// Service Route
$routes->connect(
    '/services',
    ['controller' => 'Sites', 'action' => 'listServices'],
    ['_name' => 'serv']
);

// Product Route
$routes->connect(
    '/products',
    ['controller' => 'Sites', 'action' => 'listProducts'],
    ['_name' => 'prod']
);

//...

_name is a reserved keyword in route system of CakePHP to created named routes.

Create Controller

Open project into terminal and run this bake console command to create controller.

$ bin/cake bake controller Sites --no-actions

It will create a file with name SitesController.php inside /src/Controller folder.

Open SitesController.php and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller;
use Cake\Routing\Router;

class SitesController extends AppController
{
    public function listServices()
    {
        $url = Router::url(['_name' => 'prod']);
        echo $url;
    }

    public function listProducts()
    {
        //
    }
}

To get any url value via it’s name we used here –

$url = Router::url(['_name' => 'prod']);

This is when we need inside controller files.

Get Inside Template

Create a folder Sites inside /templates folder. Create a file list_services.php inside /templates/Sites folder.

To get value of url using named value inside template files –

<?php
echo $this->Html->link(
    'Product Page Link',
    ['_name' => 'prod']
);

We hope this article helped you to learn about CakePHP 4 How To Use Named Route Tutorial 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.