CakePHP 3.x | How to change URL of your website to hide controller/action name

|
| By Webner

Requirement: While running the website in browser, the url path shows controller name followed by the action name and parameters list. In that case the url looks like:

www.xyz.com/User/showDetails/

We may come across two types of requirements.

Displaying only the action name without showing the controller name.
Displaying only the controller name without showing the action name.

Solution:

1. Displaying only the action name without showing the controller name: If you want to hide controller name from URL, follow these steps:

a. Open routes.php file in the config folder.
b. Find the piece of code in this file where you set various routes/URLs for your site. It will look like this:

Router::scope('/', function ($routes) {
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
});

c. Add this line inside the block for your specific page, for eg. ‘showDetails’

$routes->connect('/showDetails', ['controller' => 'User', 'action' => 'showDetails']);

Here, ‘User’ is the name of Controller while ‘showDetails’ is the action name inside User controller.

Alternatively, you can directly use the Router Class to set the url path for your page. The line will be written outside the above-mentioned scope block:

Router :: connect(‘/showDetails’,array('controller' => 'User', 'action' => 'showDetails']));

Result:

The new URL will now be: www.xyz.com/showDetails/

2. Displaying only the controller name without showing the action name: Conversely, to display only the controller name in URL, add below line in routes.php file inside same block as mentioned above:

Router::scope('/', function ($routes) {
$routes->connect('/user/*', ['controller' => 'User', 'action' => 'showDetails']);
});

Result:

This will show the URL as www.xyz.com/user/

Important: If required, you can also change the controller or action names in the url. Syntax for the same would be:

Changing controller name:

Router::connect(
 '/customer/:action/*', array('controller' => ‘user’)
);

The above piece of code would make sure to redirect any url which starts from /customer/actionName, to user controller.

Changing action name:

Router::scope('/', function ($routes) {
$routes->connect('/user/myDetails', ['controller' => 'User', 'action' => 'showDetails']);
});

Calling the /user/myDetails/ url would be mapped to showDetails action of user controller.

Leave a Reply

Your email address will not be published. Required fields are marked *