Magento 2 Routing

The Route will define name for a module which we can use in the url to find the module and execute the controller action.

In Magento 2, the request url will be http://phpcodez.com/index.php/front_name/controller/action

In that url, you will see the front_name which will be use to find the module. The router define this name for each module by define in routes.xml

Create custom route on frontend

To register a frontend route, we must create a routes.xml file:

File: app/code/PHPCodez/First/etc/frontend/routes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
 <!--Use router 'standard' for frontend route-->
 <router id="standard">
 <!--Define a custom route with id and frontName-->
 <route frontName="first" id="first">
 <!--The module which this route match to-->
 <module name="PHPCodez_First"/>
 </route>
 </router>
</config>

The id attribute is a unique string which will identify this route. You will use this string to declare the layout handle for the action of this module

The frontName attribute is also a unique string which will be shown on the url request.

The url to this module should be http://phpcodez.com/index.php/first/controller/action

And the layout handle for this action is: first_controller_action.xml So with this example path, you must create the action class in this folder: {namespace}/{module}/Controller/{Controller}/{Action}.php

Create custom route on admin

This route will be same as the frontend route but you must declare it in adminhtml folder with router id is admin.

File: app/code/PHPCodez/First/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
 <!--Use router 'admin' for admin route -->
 <router id="admin">
 <!--Define a custom route with id and frontName -->
 <route id="phpcodez_first" frontName="phpcodez_first">
 <!--The module which this route match to-->
 <module name="PHPCodez_First"/>
 </route>
 </router>
</config>

The url of the admin page is the same structure with frontend page, but the admin_area name will be added before route_frontName to recognize this is a admin router.

http://phpcodez.com/index.php/admin/phpcodez_first/controller/action

The controller action for admin page will be added inside of the folder Controller/Adminhtml

{namespace}/{module}/Controller/Adminhtml/{Controller}/{Action}.php

Leave a Reply

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